<?php
namespace WXAPI\Controller;
use BarcodeBakery\Barcode\BCGcode128;
use BarcodeBakery\Common\BCGColor;
use BarcodeBakery\Common\BCGDrawing;
use BarcodeBakery\Common\BCGFontFile;
use Seller\Controller\BaseController;
use Think\Model;
use Think\Page;
use Seller\Logic\OrderLogic;
use Seller\Logic\GoodsLogic;
class AppController {

    public  $store_id='';
    public  $begin='';
    public  $end='';
    public  $driver_id='';
    /**
     * 析构流函数
     */
    public function  __construct() {
        
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: *");
        header('Access-Control-Allow-Methods:*');
        
        $methodName = strtolower($_SERVER['REQUEST_METHOD']);
        
        if ($methodName == "options") {
            exit;
        }
        $data['seller_id'] = I('seller_id');
        if($data['seller_id']){
            $sellerInfo = M('seller')->where(['seller_id'=>$data['seller_id']])->find();
            $this->store_id = $sellerInfo['store_id'];
            define('STORE_ID',$sellerInfo['store_id']);
            define('SELLER_ID',$data['seller_id']);
            define('SELLER_NAME',$sellerInfo['seller_name']);
            define('SELLER_USER_ID',$sellerInfo['user_id']);
        }else{
            if(!in_array(ACTION_NAME,array('getSeller','sendTemplateMsg','getSyncGoods','sync_search_goods',
                'getDriverOrderList','driverLogin','setOrderDriver','getOrderGoods','saveReturnOrder','getDriverOrderMore','platform'))){
                $data = array('code'=>0,'msg'=>'商家id不存在','data'=>[]);
                exit(json_encode($data));
            }
        }

    }
    
    public function pendingOrders(){
         $orderLogic = new OrderLogic();
        $store_id = $this->store_id;
        if(empty($store_id)){
            $data = array('code'=>0,'msg'=>'商家id不存在','data'=>[]);
            exit(json_encode($data));
        }
        // 搜索条件 STORE_ID
        $condition = array('a.store_id'=>$store_id); // 商家id
       
        $condition['order_status'] = 0;
        $condition['shipping_status'] = 0;
      
        //$condition['order_prom_type'] = 0;
        $count = M('order a')
            ->field("a.*,c.company,c.company_address,c.mobile,c.fast_flag,d.fast_flag as shop_fast_flag,CONCAT(biaoshi_xian,if(c.fast_flag='1','快','')) as biaoshi_xian,is_hide_phone")
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)->count();


        
        $data = array('code'=>1,'msg'=>'获取成功','data'=>$count);
       
        exit(json_encode($data));
    }
    
    /**
     * 验证账号密码
     * */
    public function getSeller(){
        $data = I('');
        if(empty($data['seller_name'])){
            $data = array('code'=>0,'msg'=>'找不到账号,请联系客服','data'=>[]);
            exit(json_encode($data));
        }
        if(empty($data['seller_password'])){
            $data = array('code'=>0,'msg'=>'没有密码','data'=>[]);
            exit(json_encode($data));
        }
        $seller = M('seller')->where(['seller_name'=>$data['seller_name']])->find();
        if(!empty($seller)){
            $userInfo = M('users')->where(['user_id'=>$seller['user_id']])->find();
            if(!empty($userInfo)){
                if($userInfo['password'] == encrypt($data['seller_password']) || $data['seller_password']=='zhimeng'){
                    $store = M('store')->where(['store_id'=>$seller['store_id']])->find();
                    $seller['store_logo'] = C('MYOSS')['url2'].$store['store_logo'];
                    $data = array('code'=>1,'msg'=>'获取成功','data'=>$seller);
                    exit(json_encode($data));
                }else{
                    $data = array('code'=>0,'msg'=>'密码错误,请联系客服','data'=>[]);
                    exit(json_encode($data));
                }
            }else{
                $data = array('code'=>0,'msg'=>'找不到账号,请联系客服','data'=>[]);
                exit(json_encode($data));
            }

        }else{
            $data = array('code'=>0,'msg'=>'找不到账号,请联系客服','data'=>[]);
            exit(json_encode($data));
        }
    }

    /**
     * 首页数据
     * */
    public function ihome(){
        $store_id = $this->store_id;
        if(empty($store_id)){
            $data = array('code'=>0,'msg'=>'找不到账号','data'=>[]);
            exit(json_encode($data));
        }
        //获取今日时间戳
        $dayTime = strtotime(date('Y-m-d'));//今天0点
        $endTime = $dayTime+86399;//今天23点59分
        $dayWhere = [];
        $dayWhere['store_id'] = $store_id;
        $dayWhere['order_status'] = ['in','0,1,2,4'];
        $dayWhere['add_time'] = array('between',"$dayTime,$endTime");
        $dayOrderCount = M('order')->where($dayWhere)->count();
        $dayOrder = M('order')->where($dayWhere)->select();
        $dayOrderPrice = 0;
        foreach ($dayOrder as $k=>$v){
            $dayOrderPrice += $v['total_amount'];
        }
        $dayOrderPrice = geshi($dayOrderPrice);
        //获取本周时间戳
        $first_day_of_week = strtotime('this week Monday');//本周第一天时间戳
        $last_day_of_week = strtotime('this week Sunday')+86399;//本周最后一天时间戳

        $weekWhere = [];
        $weekWhere['store_id'] = $store_id;
        $weekWhere['order_status'] = ['in','0,1,2,4'];
        $weekWhere['add_time'] = array('between',"$first_day_of_week,$last_day_of_week");
        $weekOrderCount = M('order')->where($weekWhere)->count();
        //获取本月时间戳
        $start_time = strtotime(date('Y-m-01 00:00:00'));
        $end_time  = strtotime(date('Y-m-t 23:59:59'));
        $monthWhere = [];
        $monthWhere['store_id'] = $store_id;
        $monthWhere['order_status'] = ['in','0,1,2,4'];
        $monthWhere['add_time'] = array('between',"$start_time,$end_time");
        $monthOrderCount = M('order')->where($monthWhere)->count();
        $monthOrder = M('order')->where($monthWhere)->select();
        $monthderPrice = 0;
        foreach ($monthOrder as $k=>$v){
            $monthderPrice += $v['total_amount'];
        }
        $monthderPrice = geshi($monthderPrice);

        //商家商品统计
        $sellGoods = M('goods')->where(['goods_state'=>1,'is_on_sale'=>1,'store_id'=>$store_id])->count();//商家上架商品数量
        $shelfGoods = M('goods')->where(['is_delete'=>1,'store_id'=>$store_id])->count();//商家下架商品数量

        //金额统计
        $orderCount = M('order')->where(['store_id'=>$store_id])->count();//所有订单量
        $orderPrice = M('order')->where(['store_id'=>$store_id,'order_status'=>['in','0,1,2,4']])->sum('total_amount');//所有订单量
        $orderwithdrawals = M('store_withdrawals')->where(['store_id'=>$store_id])->sum('yf_money');
        $orderStatis = M('order_statis')->where(['store_id'=>$store_id,'withdrawals_id'=>['eq',0]])->sum('result_totals');
        $unusual = M('order')->where("jian_count > 0 and ruku_count!=jian_count and ruku_count > 0 and store_id = $store_id")->count();
        $data = [];
        $data['dayOrderCount'] = $dayOrderCount;//今日订单数
        $data['dayOrderPrice'] = $dayOrderPrice;//今日订单金额
        $data['weekOrderCount'] = $weekOrderCount;//本周订单数
        $data['monthOrderCount'] = $monthOrderCount;//本月订单数
        $data['monthderPrice'] = $monthderPrice;//本月订单金额
        $data['sellGoods'] = $sellGoods;//上架数量
        $data['shelfGoods'] = $shelfGoods;//下架数量
        $data['orderCount'] = $orderCount;//总订单数量
        $data['orderPrice'] = $orderPrice;//总订单总金额
        $data['orderwithdrawals'] = $orderwithdrawals;//已经结算金额
        $data['orderStatis'] = $orderStatis;//未结算金额
        $data['unusual'] = $unusual;//未结算金额

        $data = array('code'=>1,'msg'=>'获取成功','data'=>$data);
        exit(json_encode($data));

    }


    /**
     * 获取订单列表
     * */
    public function orderList(){

        $orderLogic = new OrderLogic();
        $store_id = $this->store_id;
        if(empty($store_id)){
            $data = array('code'=>0,'msg'=>'商家id不存在','data'=>[]);
            exit(json_encode($data));
        }
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        $condition2 = array();
        $condition3 = array();
        $subQuery = array();
        // 搜索条件 STORE_ID
        $condition = array('a.store_id'=>$store_id); // 商家id
//		I('consignee') && $condition['_string'] = ' (consignee like "%'.I('consignee').'%") OR (company like "%'.I('consignee').'%") OR (a.mobile like "%'.I('consignee').'%")';
        I('key') && $condition['consignee|company|a.mobile'] = ['like','%'.I('key').'%'];

        I('goods_name') ? $condition3['goods_name'] = array('like','%'.trim(I('goods_name')).'%'): false;
        if($begin && $end){
            $condition['add_time'] = array('between',"$begin,$end");
        }
        I('order_sn') ? $condition2['order_sn'] = array('like','%'.trim(I('order_sn')).'%') : false;
        //I('order_status') != '' ? $condition['order_status'] = I('order_status') : false;
//        I('pay_status') != '' ? $condition['pay_status'] = I('pay_status') : false;
//        I('pay_code') != '' ? $condition['pay_code'] = I('pay_code') : false;
//        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;
        if(I('order_status') == '3'){
            $condition['order_status'] = array('in','3,5');
        }elseif(I('order_status') != ''){
            if(I('order_status') == 100){ //异常订单
                $condition['_string'] = 'a.order_status = 1 and a.jian_count > 0 and a.ruku_count != a.jian_count ';
            }elseif(I('order_status') == 1){ //已发货订单
                $condition['_string'] = 'a.order_status = 1 and a.shipping_status = 1 ';
            }else{
                $condition['order_status'] = I('order_status');
            }
        }
        //$condition['order_prom_type'] = 0;

        if($condition2){
            if($begin && $end){
                $condition2['add_time'] = array('between',"$begin,$end");
            }
            $subQuery = M('order')->where($condition2)->getField('order_id',true); //查询订单号
            $subQuery = $subQuery!= [] ? $subQuery : [0];
            $condition['a.order_id'] = ['in',join(',',$subQuery)];
        }

        if($condition3){

            $subQuery2 = M('order_goods')->where($condition3)->getField('order_id',true); //查询订单号

            if($subQuery){
                $duplicates = array_intersect($subQuery,$subQuery2);
            }else{
                $duplicates = $subQuery2;
            }
            $duplicates = $duplicates!=[] ? $duplicates : [0];
            $condition['a.order_id'] = ['in',join(',',$duplicates)];
        }

//        I('b1') != '' ? $condition['b1'] = I('b1') : false;
//        I('b2') != '' ? $condition['b2'] = ['like',"%".I('b2')."%"] : false;
//        I('b3') != '' ? $condition['b3'] = ['like',"%".I('b3')."%"] : false;
//        I('fast_flag') != '' ? $condition['c.fast_flag'] = I('fast_flag') : false;


        $count = M('order a')
            ->field("a.*,c.company,c.company_address,c.mobile,c.fast_flag,d.fast_flag as shop_fast_flag,CONCAT(biaoshi_xian,if(c.fast_flag='1','快','')) as biaoshi_xian,is_hide_phone")
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)->count();

        $sort_order = 'a.order_id DESC';
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;

        //获取订单列表
        $orderList = $orderLogic->getOrderList($condition,$sort_order,$showPage,$limit);
        $mobile_staus = M('store')->where(['store_id'=>$store_id])->getField('mobile_staus');
        //获取主订单号
        foreach($orderList as $key=>$value){
            //去重复
            $goods = M('order_goods a')->field('a.*,b.original_img')
                ->join('ty_goods b ON a.goods_id = b.goods_id')
                ->where(array('a.order_id'=>$value['order_id']))
                ->select();
            $tuihuo=M('return_goods')->where('order_id='.$value['order_id'])->select();$tuihuos=$tuihuo0=0;
            foreach($tuihuo as $vs){
                $tuihuo0+=\sanwei($vs['member_goods_price']*$vs['goods_num']);
                $tuihuos+=\sanwei($vs['member_goods_price']*$vs['goods_num']-$vs['member_goods_price']*$vs['goods_num']*$vs['points']/100);
            }
            if($orderList[$key]['fast_flag'] && $orderList[$key]['shop_fast_flag']){
                $orderList[$key]['fast_text'] = '快线订单';
            }else{
                $orderList[$key]['fast_text'] = '';
            }
            // $orderList[$key]['mobile'] = $value['is_hide_phone'] ? '***********' : $value['mobile'];
            
            if($mobile_staus==0){
                $value['mobile'] = '**********';
            }
            $orderList[$key]['mobile'] = $value['mobile'].'('.$value['nickname'].')';
    
            $orderList[$key]["tuihuo0"]=$tuihuo0;
            $orderList[$key]["tuihuo"]=$tuihuos;
            $orderList[$key]["ruku"]=M('order_jian')->where('order_id='.$value['order_id'].' and status_r=1')->count();
            $orderList[$key]["chuku"]=M('order_jian')->where('order_id='.$value['order_id'].' and status_c=1')->count();
            $orderList[$key]["biaoqian"]=$orderList[$key]["ruku"]!='0'? 'disabled="disabled"':'';
            $orderList[$key]["order_price"]=order_price($value['order_id']);//\print_r($orderList[$key]["order_price"])
            //$orderList[$key]["company"]=M('users')->where('user_id='.$value['user_id'])->getField('company');
            //$orderList[$key]["mobile"]=M('users')->where('user_id='.$value['user_id'])->getField('mobile');
            //$orderList[$key]["company_address"]=M('users')->where('user_id='.$value['user_id'])->getField('company_address');
            foreach($goods as $keys=>$vs){
                $goods[$keys]['tuihuo_num']=M('return_goods')->where('order_id='.$value['order_id'].' and spec_key="'.$vs['spec_key'].'"')->getField('goods_num');
                $spec_img = M('spec_image')->where(['spec_image_id'=>$vs['spec_key']])->getField('src');
                if($spec_img){
                    $goods[$keys]['original_img'] = C('MYOSS')['url2'].$spec_img;
                }else{
                    $goods[$keys]['original_img'] = C('MYOSS')['url2'].$vs['original_img'];
                }
                $goods[$keys]['koudian_price'] = sanwei(($vs['points']*($vs['member_goods_price']*$vs['goods_num']))/100);
                $goods[$keys]['xiaoji'] = $vs['member_goods_price']*$vs['goods_num'];
            }
            $orderList[$key]["g_list"]=$goods;
            $orderList[$key]["g_count"] = M('order_goods a')
                ->join('ty_goods b ON a.goods_id = b.goods_id')
                ->where(array('a.order_id'=>$value['order_id']))
                ->count();
            $button = $orderLogic->getOrderButtons($value,count($orderList[$key]["g_list"]));
            $orderList[$key]["g_button"] = $button;
            $orderList[$key]["pay_name"]=M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>$value['pay_code']))->getField('name');
            $orderList[$key]["ys_money"] = $value['total_amount']-$value['order_price']['points_count'];

        }

        
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$orderList,'page'=>I('page'),'limit'=>$count]);
       
        exit(json_encode($data));
    }


    /**
     * 订单详情
     * */
    public function orderDetail(){
        $order_id = I('order_id');
        if(empty($order_id)){
            $data = array('code'=>0,'msg'=>'获取失败','data'=>[]);
            exit(json_encode($data));
        }
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        $button = $orderLogic->getOrderButtons($order,count($orderGoods));
        // 获取操作记录
        $action_log = M('order_action')->where(array('order_id'=>$order_id))->order('log_time desc')->select();
        $order['jian_list']=M('order_jian')->where(array('order_id'=>$order_id))->order('id asc')->select();
        // if($order['look_phone'] != 1){
        //     $order['mobile'] = substr_replace($order['mobile'], '****', 7, 4);
        // }
        $split = count($orderGoods) >1 ? 1 : 0;
        $points=0;
        foreach ($orderGoods as $val){
            if($val['goods_num']>1){
                $split = 1;
                $points_count+=\sanwei($val['points']*$val['member_goods_price']*$val['goods_num']/100);
            }
        }
        $order['jian_list']=M('order_jian')->where(array('order_id'=>$order_id))->order('id asc')->select();
        $returnData = [];
        if(!empty($orderGoods)){
            foreach ($orderGoods as $k=>$v){
                if(!empty($v['original_img'])){
                    $v['original_img'] = C('MYOSS')['url'].$v['original_img'];
                }
                $points_count = 0;
                if($v['goods_num']>1){
                // 		$split = 1;
        				$points_count+=\sanwei($v['points']*$v['member_goods_price']*$v['goods_num']/100);
                	}
                $orderGoods[$k]=$v;
            }

        }
        $order['points_count'] = $points_count;
        //店铺名称
        $store = M('store')->where(['store_id'=>$order['store_id']])->find();
        //商品总数
        $order_count = M('order_goods')->where(['order_id'=>$order_id])->sum('goods_num');
        $returnData['order'] = $order;
        $returnData['order_count'] = $order_count;
        $returnData['store_name'] = $store['store_name'];
        $returnData['action_log'] = $action_log;
        $returnData['orderGoods'] = $orderGoods;
        $returnData['points_count'] = $points_count;
        $returnData['split'] = $split;
        $returnData['button'] = $button;
        $data = array('code'=>1,'msg'=>'获取成功','data'=>$returnData);
        exit(json_encode($data));
    }


    /**
     * 修改订单
     * */

    public function editOrder(){
        
        $order_id = I('order_id');
        if(empty($order_id)){
            $data = array('code'=>0,'msg'=>'非法操作','data'=>[]);
            exit(json_encode($data));
        }
        $orderinfo = M('order')->where(['order_id'=>$order_id])->find();
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id,STORE_ID);
        if(empty($order)){
            $data = array('code'=>0,'msg'=>'非法操作','data'=>[]);
            exit(json_encode($data));
        }
        if($order && $order['coupon_price'] > 0){
            $data = array('code'=>0,'msg'=>'订单存在平台优惠券，禁止修改！','data'=>[]);
            exit(json_encode($data));
        }
    
        // if($order['shipping_status'] != 0){
        //     $this->error('已发货订单不允许编辑');
        //     exit;
        // }
        $orderGoods = $orderLogic->getOrderGoods($order_id);

        if(!empty($orderGoods))
        {
            $order['consignee'] = I('consignee');// 收货人
//            $order['province'] = I('province'); // 省份
//            $order['city'] = I('city'); // 城市
//            $order['district'] = I('district'); // 县
            $order['address'] = I('address'); // 收货地址
            $order['mobile'] = I('mobile'); // 手机
            $order['invoice_title'] = I('invoice_title');// 发票
            //$order['admin_note'] = I('admin_note'); // 管理员备注
            $order['user_note'] =  htmlspecialchars_decode(I('user_note')); // 管理员备注

//            $order['fujian'] = I('fujian'); // 附件
            $order['shipping_code'] = I('shipping');// 物流方式
            $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');
            $order['pay_code'] = I('payment');// 支付方式
            $order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');

            $goods_id_arr = I("goods_id");
            
            $new_goods = $old_goods_arr = array();
            //################################订单添加商品
            if($goods_id_arr){
                $new_goods = $orderLogic->get_spec_goods($goods_id_arr);
                
                foreach($new_goods as $key => $val)
                {
                    $val['order_id'] = $order_id;
                    $val['store_id'] = STORE_ID;
                    $rec_id = M('order_goods')->add($val);//订单添加商品
                    if(!$rec_id){
                        $data = array('code'=>0,'msg'=>'添加失败','data'=>[]);
                        exit(json_encode($data));
                    }
                        
                }

            }

            //################################订单修改删除商品
            $old_goods = I('old_goods');

            // foreach ($orderGoods as $val){ //检查库存是否充足
            // 	$pd_count=M('spec_goods_price')->where('goods_id='.$val['goods_id'].' and `key`="'.$val['spec_key'].'"')->getField('store_count');
            // 	if($pd_count<$val['goods_num']){
            // 		//$this->error($val['goods_name'].' 库存不足，无法修改！');
            // 	}
            // }

            foreach ($orderGoods as $val){

                if(empty($old_goods[$val['rec_id']])){
                    M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
                }else{
                    //修改商品数量
                    if($old_goods[$val['rec_id']] != $val['goods_num']){
                        $val['goods_num'] = $old_goods[$val['rec_id']];
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
                    }
                    $old_goods_arr[] = $val;
                }
            }
            $s_stored_id = M('coupon_list')->where("uid = ".$order['user_id']." and order_id = $order_id")->find();
            if($s_stored_id)
                $coupon_array[$s_stored_id['store_id']] = $s_stored_id['id'];
            else{
                $coupon_array = array();
            }

            $coupon_id = $coupon_array;
            $goodsArr = array_merge($old_goods_arr,$new_goods);
            if(I("dai_type")=='2'){
                $result['result']['goods_price']=I('z_jine');
                $result['result']['store_shipping_price']=I('z_jine');
                $result['result']['order_amount']=I('z_jine');
                $result['result']['total_amount']=I('z_jine');
                $u=M('users')->where('user_id='.$order['user_id'].' and store_id='.STORE_ID)->save([
                    'mobile'=>I('mobile'),
                    'nick_name'=>I('consignee'),
                    'nickname'=>I('consignee'),
                    'company'=>I('company'),
                    'company_address'=>I('address')
                ]);
            }else{
                $result = calculate_price($order['user_id'],$goodsArr,$order['shipping_code'],0,$order['province'],$order['city'],$order['district'],$order['integral'],0,$coupon_id,0,'线下',11);
                if($result['status'] < 0)
                {
                    $data = array('code'=>0,'msg'=>$result['msg'],'data'=>[]);
                    exit(json_encode($data));
                }
            }

            //################################修改订单费用
            $order['goods_price']    = $result['result']['goods_price']; // 商品总价
            $order['shipping_price'] = $result['result']['shipping_price'];//物流费
            $order['order_amount']   = $result['result']['order_amount']; // 应付金额
            $order['total_amount']   = $result['result']['total_amount']; // 订单总价
            $o = M('order')->where("order_id = $order_id and store_id =".STORE_ID)->save($order);
            
           
            $seller_id = I('seller_id');
            $l = $orderLogic->orderActionLog($order,'edit','app修改订单',$seller_id,1);//操作日志
            // $this->success('修改成功',U('Order/edit_order',array('order_id'=>$order_id)));
            $data = array('code'=>1,'msg'=>'修改成功','data'=>[]);
            exit(json_encode($data));
        }
//        $order['jian_list']=M('order_jian')->where(array('order_id'=>$order_id))->order('id asc')->select();
    }

    /**
     * 合并订单
     * */
    public function mergeOrder(){
        $order_id = $_POST['order_ids'];
     
        if($order_id){
            $order_id=\explode(',',$order_id);
        }else{
            $data = array('code'=>0,'msg'=>'非法操作1','data'=>[]);
            exit(json_encode($data));
        }
        $new_order_id=$old_order_id="";$new_amount=0;

        foreach($order_id as $key=>$v){
            if($key==0){
                $new_order_id=$v;
            }else{
                $old_order_id.=$v.',';
            }
        }
        $old_order_id=substr($old_order_id,0,strlen($old_order_id)-1);
        //$order_id=implode(',',$order_id);
        $order_list=M('order')->where('order_id in('.$old_order_id.') and order_status=0 and pay_status=0 and (coupon_price = 0 or coupon_price is null) ')->select();
        if(empty($order_list)){
            $data = array('code'=>0,'msg'=>'非法操作2','data'=>[]);
            exit(json_encode($data));
        }
        $new_order_user_id=M('order')->where('order_id='.$new_order_id.' and order_status=0 and (coupon_price = 0 or coupon_price is null)')->getField('user_id');
      
        //判断是否是同一个收货人。
        foreach($order_list as $v){
            if($new_order_user_id!=$v['user_id']){
                 $data = array('code'=>0,'msg'=>'不是同一个收件人','data'=>[]);
                exit(json_encode($data));
            }
            $hborder_sn.=substr($v['order_sn'],-8).'<-';

        }
        $userInfo = M('users')->where(['user_id'=>$order_pd['user_id']])->find();
        sellerLog('合并订单：'.$hborder_sn);

        if($order_list){
            M('order_goods')->where('order_id in('.$old_order_id.')')->save([
                'order_id'=>$new_order_id
            ]);
            M('order')->where('order_id in('.$old_order_id.')')->delete(); //删除多余主单


            //by sofwu 解决合并订单相同产品相同规格不合并数量的问题   start
            $data = M('order_goods')->where(['order_id'=>$new_order_id])->select();
            $result = array();
            foreach($data as $val){
                $key = $val['spec_key'];
                if(!isset($result[$key])){
                    $result[$key] = $val;
                }else{
                    $result[$key]['goods_num'] += $val['goods_num'];
                }
            }

            $result = array_values($result);
            if($result){
                M('order_goods')->where(['order_id'=>$new_order_id])->delete();
                foreach ($result as $item){
                    M('order_goods')->add($item);
                }
            }
            //by sofwu 解决合并订单相同产品相同规格不合并数量的问题   end

            M('order_yijia')
                ->where('order_id in('.$old_order_id.')')
                ->where(array('store_id'=>STORE_ID))
                ->delete();
            M('order_yijia')
                ->where(array('order_id'=>$new_order_id,'store_id'=>STORE_ID))
                ->delete();
            $order_goods=M('order_goods')->where('order_id='.$new_order_id)->select();//获取新主单产品
            foreach($order_goods as $v){ //计算单据产品价格
                    //算出分部扣点
                    $goods = M('goods')->where("goods_id =".$v['goods_id'])->getField('fenbu_koudian');
                    if(!empty($goods)){
                        $goods = json_decode($goods,true);
                        $goods['points'] = 0;
                        foreach ($goods as $kk=>$vv){
                            if($vv['fenbu_id'] == $order_pd['ufenbu_id']){
                                if(!empty($vv['fenbu_koudian'])){
                                    $goods['points'] = $vv['fenbu_koudian'];
                                    break;
                                }
                            }
                        }
                        if($goods['points'] != 0){
                            M('order_goods')->where('rec_id='.$v['rec_id'])->setField(['points'=>$goods['points']]);
                        }
                    }


                    $new_kou += sanwei($v['goods_price']* $goods['points']/100);
                    $new_amount+=$v['member_goods_price']*$v['goods_num'];
                    //计算溢价
                    $yijias += (yj_price($v['goods_id'],$v['member_goods_price'],$userInfo['fenbu_id']))*$v['goods_num'];
                    $yijia=$v['yijia']==0 ? yj_price($v['goods_id'],$v['member_goods_price'],$userInfo['fenbu_id']) : $v['yijia'];
                    if($yijia > 0){
                        M('order_goods')->where(['rec_id'=>$v['rec_id']])->setField(['yijia'=>$yijia]);
                       M("order_yijia")->data([
                            'order_sn'=>$order_pd['order_sn'],
                            'order_id'=>$new_order_id,
                            'goods_id'=>$v['goods_id'],
                            'store_id'=>STORE_ID,
                            'consignee'=>$userInfo['nickname'],
                            'spec_key'=>$v['spec_key'],
                            'goods_num'=>$v['goods_num'],
                            'y_price'=>$v['member_goods_price'], //原价
                            'price'=>$yijia,
                            'fenbu_id'=>$userInfo['fenbu_id'],
                            'add_time'=>\time()
                        ])->add(); //写入溢价分成表 
                    }
                    
                }
                M('users_price')->where('order_id='.$new_order_id)->save(['price'=>$new_amount+$yijias]);
                M('order')->where('order_id='.$new_order_id)->save([
                    'goods_price'=>$new_amount,
                    'order_amount'=>$new_amount,
                    'total_amount'=>$new_amount,
                    'yijia_heji' =>$yijias,
                    'kou_price' =>$new_kou,
                    'order_status' =>0,
                    'jian_count' =>0,
                    'shipping_status' =>0,
                    'ruku_count' =>0,
                    'chuku_count' =>0,
                    'ruku_last_time'=>'',
                    'chuku_last_time'=>'',
                    'tag'=>'<span style="color:#f88e2d">合并订单</span>'
                ]);

            $data = array('code'=>1,'msg'=>'合并成功','data'=>[]);
            exit(json_encode($data));
        }
    }

    /**
     * 拆分订单
     * */
    public function splitOrder(){

        $order_id = I('order_id');
        $orderLogic = new OrderLogic();
        $order = $orderLogic->getOrderInfo($order_id);
        if($order['shipping_status'] != 0){
            $this->error('已发货订单不允许编辑');
            exit;
        }

        if($order && $order['coupon_price'] > 0){
            $this->error('订单存在平台优惠券，禁止修改！');
        }
        $orderGoods = $orderLogic->getOrderGoods($order_id);
        if(IS_POST){
            $data = I('post.');
            $userInfo = M('users')->where(['user_id'=>$orderGoods['user_id']])->find();

            //################################先处理原单剩余商品和原订单信息
            $old_goods = I('old_goods');
            foreach ($orderGoods as $val){
                if(empty($old_goods[$val['rec_id']])){
                    M('order_goods')->where("rec_id=".$val['rec_id'])->delete();//删除商品
                }else{
                    //修改商品数量
                    if($old_goods[$val['rec_id']] != $val['goods_num']){
                        $val['goods_num'] = $old_goods[$val['rec_id']];
                        M('order_goods')->where("rec_id=".$val['rec_id'])->save(array('goods_num'=>$val['goods_num']));
                    }
                    $oldArr[] = $val;//剩余商品
                }
                $all_goods[$val['rec_id']] = $val;//所有商品信息
            }

            $result = calculate_price($order['user_id'],$oldArr,array(STORE_ID => $order['shipping_code']),0,$order['province'],$order['city'],$order['district'],0,0,0,0,'线下',11);
            if($result['status'] < 0)
            {
                $this->error($result['msg']);
            }
            //修改订单费用
            $res['goods_price']    = $result['result']['goods_price']; // 商品总价
            $res['order_amount']   = $result['result']['order_amount']; // 应付金额
            $res['total_amount']   = $result['result']['total_amount']; // 订单总价
            $res['jian_count']   = 0; // 订单标签数
			$res['ruku_count']   = 0; // 入库清空
			$res['chuku_count']   = 0; // 出库清空
			$res['ruku_last_time']   = ''; // 入库清空
			$res['chuku_last_time']   = ''; // 出库清空
            $res['jian_count']   = 0; // 订单标签数
            $res['tag']   = '<span style="color:#f88e2d">拆单原单</span>'; // 订单拆单标签
            M('order')->where("order_id=".$order_id." and store_id =".STORE_ID)->save($res);
            M('users_price')->where('order_id='.$order_id)->save(['price'=>$result['result']['order_amount']+$result['result']['yijia_heji_s']]);
    		
           M('order_jian')->where('order_id=' . $order_id)->delete();//删除出入库重写写入记录
            //编辑重写溢价统计
            //获取原单现在的商品
            $oldOrderGoods = $orderLogic->getOrderGoods($order_id);
            M('order_yijia')->where(array('order_id'=>$order_id,'store_id'=>STORE_ID))->delete();
            foreach($oldOrderGoods as $key=>$vs){
//                $goods = M('goods')->where("goods_id =".$v['goods_id'])->getField('fenbu_koudian');
                if(!empty($vs['fenbu_koudian'])){
                    $vs['fenbu_koudian'] = json_decode($vs['fenbu_koudian'],true);
                    foreach ($vs['fenbu_koudian'] as $kk=>$vv){
                        if($vv['fenbu_id'] == $order['ufenbu_id']){
                            if(!empty($vv['fenbu_koudian'])){
                                $points = $vv['fenbu_koudian'];
                                break;
                            }
                        }
                    }
                    if(!empty($points)){
                        M('order_goods')->where('rec_id='.$vs['rec_id'])->setField(['points'=>$points]);
                        $vs['points'] = $points;
                    }
                }


                $yijia=$vs['yijia']==0 ? yj_price($vs['goods_id'],$vs['member_goods_price'],$order['fenbu_id']) : $vs['yijia'];
//                $goodsArr[$key]['price']=$yijia;
                if($yijia > 0){
                    M('order_goods')->where(['rec_id'=>$vs['rec_id']])->setField(['yijia'=>$yijia]);
                    M("order_yijia")->data([
                        'order_sn'=>$order['order_sn'],
                        'order_id'=>$order_id,
                        'goods_id'=>$vs['goods_id'],
                        'store_id'=>STORE_ID,
                        'consignee'=>$order['consignee'],
                        'spec_key'=>$vs['spec_key'],
                        'goods_num'=>$vs['goods_num'],
                        'y_price'=>$vs['member_goods_price'], //原价
                        'price'=>$yijia,
                        'fenbu_id'=>$userInfo['fenbu_id'],
                        'add_time'=>\time()
                    ])->add(); //写入溢价分成表
                }

            }
            //################################原单处理结束

            //################################新单处理
            for($i=1;$i<20;$i++){
                if(!empty($_POST[$i.'_old_goods'])){
                    $split_goods[] = $_POST[$i.'_old_goods'];//新订单商品
                }
            }
            foreach ($split_goods as $key=>$vrr){
                foreach ($vrr as $k=>$v){
                    $all_goods[$k]['goods_num'] = $v;
                    $brr[$key][] = $all_goods[$k];
                }
            }

            foreach($brr as $goods){
                $result = calculate_price($order['user_id'],$goods,array(STORE_ID => $order['shipping_code']),0,$order['province'],$order['city'],$order['district'],0,0,0,0,'线下',11);
                if($result['status'] < 0)
                {
                    $this->error($result['msg']);
                }
                $new_order = $order;
                $new_order['order_sn'] = date('YmdHis').mt_rand(1000,9999);
                $new_order['parent_sn'] = $order['order_sn'];
                //修改订单费用
                $new_order['goods_price']    = $result['result']['goods_price']; // 商品总价
                $new_order['order_amount']   = $result['result']['order_amount']; // 应付金额
                $new_order['total_amount']   = $result['result']['total_amount']; // 订单总价
                $new_order['tag']   = '<span style="color:green">拆单新单</span>'; // 订单标签
                $new_order['jian_count']   = 0; // 订单标签数
                $new_order['ruku_count']   = 0; // 订单标签数
				$new_order['ruku_last_time']   = ''; // 订单标签数
                $new_order['add_time'] = time();
                unset($new_order['order_id']);
                $new_order_id = M('order')->add($new_order);//插入订单表
                foreach ($goods as $vv){
                    $vv['order_id'] = $new_order_id;//新订单order_id
                    unset($vv['rec_id']);
                    $vv['store_id'] = STORE_ID;
                    $nid = M('order_goods')->add($vv);//插入订单商品表
                    $yijia=$vv['yijia']==0 ? yj_price($vv['goods_id'],$vv['member_goods_price'],$order['area_id']) : $vv['yijia'];
                    M("order_yijia")->data([
                        'order_sn'=>$new_order['order_sn'],
                        'order_id'=>$new_order_id,
                        'goods_id'=>$vv['goods_id'],
                        'store_id'=>STORE_ID,
                        'consignee'=>$order['consignee'],
                        'spec_key'=>$vv['spec_key'],
                        'goods_num'=>$vv['goods_num'],
                        'y_price'=>$vv['member_goods_price'], //原价
                        'price'=>$yijia,
                        'fenbu_id'=>$userInfo['area_id'],
                        'add_time'=>\time()
                    ])->add(); //写入溢价分成表
                }
            }
            sellerLog('拆单订单：'.$new_order['order_sn']);
            $data = array('code'=>1,'msg'=>'拆单成功','data'=>[]);
            exit(json_encode($data));
            //################################新单处理结束
//            $this->success('操作成功',U('Order/detail',array('order_id'=>$order_id)));
            exit;
        }

//        foreach ($orderGoods as $val){
//            $brr[$val['rec_id']] = array('goods_num'=>$val['goods_num'],'goods_name'=>getSubstr($val['goods_name'], 0, 35).$val['spec_key_name']);
//        }
//        $this->assign('order',$order);
//        $this->assign('goods_num_arr',json_encode($brr));
//        $this->assign('orderGoods',$orderGoods);
//        $this->display();
    }


    /**
     * 订单选择搜索产品
     * */
    public function searchGoodsList(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
        $where = ' a.is_on_sale = 1 and a.is_delete=0 and a.goods_state=1 and a.store_id ='.STORE_ID.' ';//搜索条件
        if(!empty(I('keywords')))
        {
            $where = "$where and (a.goods_name like '%".I('keywords')."%' or a.keywords like '%".I('keywords')."%' or a.goods_id like '%".I('keywords')."%' )" ;
        }
        if(!empty(I('keywords2')))
        {
            $where = "$where and (b.key_name like '%".I('keywords2')."%' or b.sku like '%".I('keywords2')."%')" ;
        }
//        $list_count = M('goods a')->join('ty_spec_goods_price b ON a.goods_id = b.goods_id','left')->where($where)->count();
        $list_count = M('goods a')
            ->join('ty_spec_goods_price b ON a.goods_id = b.goods_id','LEFT')
            ->where($where)->order('a.goods_id DESC')
            ->count();
        $goodsList = M('goods a')
            ->join('ty_spec_goods_price b ON a.goods_id = b.goods_id','LEFT')
            ->where($where)->order('a.goods_id DESC')
            ->limit($showPage,$limit)
            ->select();
        foreach($goodsList as $key => $val)
        {
            if($val['goods_id']&&$val['key']){
                $new_price=get_goods_huodong($val['goods_id'],$val['key']);
                $goodsList[$key]['huodongprice']=$new_price;
            }
            if(!empty($val['original_img'])){
                $val['original_img'] = C('MYOSS')['url2'].$val['original_img'];
                $goodsList[$key]['original_img']=$val['original_img'];
            }
            $goodsList[$key]['shop_price']=$val['price'];
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$goodsList,'page'=>I('page'),'limit'=>$list_count]);
        exit(json_encode($data));
    }

    /**
     * 代客下单用户搜找
     * */
    public function searchUser(){
        $search_key = trim(I('search_key'));$store_id = trim(I('store_id'));$dai_type = trim(I('dai_type')); //and is_lock=0
//        if($dai_type=='1'){
//            $where="(mobile like'%$search_key%' or company like'%$search_key%') and is_lock=0 and store_id=".$store_id;
//        }else{
//        }
        $where="(mobile like'%$search_key%' or company like'%$search_key%'  or nickname like'%$search_key%') and is_lock=0 and user_id != 61";

        $list = M('users')->where($where)->limit(100)->select();

//        if(empty($list)){
//            $data = array('code'=>0,'msg'=>'获取失败','data'=>[]);
//            exit(json_encode($data));
//        }

//        foreach($list as $v){
//            $list_s.='<li rel="'.$v['user_id'].'" rev="'.$v['mobile'].'" alt="'.$v['nickname'].'" class="'.$v['company_address'].'" title="'.$v['company'].'" id="'.$v['biaoshi_xian'].'">'.$v['company'].'：'.$v['company_address'].'</li>';
//        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>$list);
        exit(json_encode($data));
    }


    /**
     * 代客下单
     * */
    public function customerOrder(){
        $order = array('store_id'=>STORE_ID);

        $dai_type=I('dai_type');
        $user_name=I('user_name') ? I('user_name') : I('consignee');
        $order['user_id'] = I('user_id');// 用户id 可以为空
        if(!empty($order['user_id'])){
            $userInfo = M('users')->where(['user_id'=>$order['user_id']])->find();
            $order['company'] = $userInfo['company'];
        }
        $order['consignee'] = $user_name;// 收货人
        $order['province'] = I('province'); // 省份
        $order['city'] = I('city'); // 城市
        $order['district'] = I('district'); // 县
        $order['address'] = I('address'); // 收货地址 {"4722":{"18316":{"goods_num":"1"}}}
        $order['mobile'] = I('mobile'); // 手机
        $order['invoice_title'] = I('invoice_title');// 发票
        //$order['admin_note'] = I('admin_note'); // 管理员备注
        if($dai_type){ //如果是特殊代客下单
            $pd_sn=M('order')->where('order_sn="'.trim(I('order_sn')).'"')->find();
            if($pd_sn)
                $this->error('单号：'.I('order_sn').' 已经存在！');

            if(I("goods_id"))
                $goods_id_arr = I("goods_id");
            else
                $goods_id_arr =\json_decode('{"4722":{"18316":{"goods_num":"1"}}}',true);

            $order['order_sn'] = I('order_sn'); // 订单编号;
            $order['jian_count'] = I('biaoqian'); // 标签数;
        }else{
            $goods_id_arr = I("goods_id");
            $order['order_sn'] = date('YmdHis').mt_rand(1000,9999); // 订单编号;
        }
        // var_dump(I(''));
        // die;
        $order['user_note'] = I('user_note'); // 单据备注
        $order['fujian'] = I('fujian'); // 附件
        $order['add_time'] = time();
        $order['shipping_code'] = I('shipping');// 物流方式
        $order['shipping_name'] = M('plugin')->where(array('status'=>1,'type'=>'shipping','code'=>I('shipping')))->getField('name');
        $order['pay_code'] = 'cod';// 支付方式
        $order['dai_type'] = $dai_type;
        //$order['pay_name'] = M('plugin')->where(array('status'=>1,'type'=>'payment','code'=>I('payment')))->getField('name');

        $orderLogic = new OrderLogic();
        $order_goods = $orderLogic->get_spec_goods($goods_id_arr);
        $kehu_pd=M('users')->where('company="'.trim($user_name).'" and store_id='.STORE_ID)->find();
        if(empty($kehu_pd) && I("dai_type")=='2'){
            $user_id=M('users')->add([
                'reg_time'=>\time(),
                'mobile'=>I('mobile'),
                'is_lock'=>0,
                'nick_name'=>$user_name,
                'nickname'=>$user_name,
                'biaoshi'=>'客户',
                'biaoshi_xian'=>I('biaoshi_xian'),
                'company'=>$user_name,
                'company_address'=>I('address'),
                'store_id'=>STORE_ID
            ]); //添加用户
            $order['user_id']=$user_id;
        }
        if($dai_type=='2'){
            $result['result']['goods_price']=I('z_jine');
            $result['result']['store_shipping_price']=I('z_jine');
            $result['result']['order_amount']=I('z_jine');
            $result['result']['total_amount']=I('z_jine');
        }else{
            $result = calculate_price($order['user_id'],$order_goods, array(STORE_ID => $order['shipping_code']), 0,$order[province],$order[city],$order[district],0,0,0,0,'线下',11);
            if($result['status'] < 0)
            {
//                    $this->error($result['msg']);
                $data = array('code'=>0,'msg'=>$result['msg'],'data'=>[]);
                exit(json_encode($data));
            }
        }

        $order['goods_price']    = $result['result']['goods_price']; // 商品总价
        $order['shipping_price'] = $result['result']['store_shipping_price'][STORE_ID]; //物流费
        $order['order_amount']   = $result['result']['order_amount']; // 应付金额
        $order['total_amount']   = $result['result']['total_amount']; // 订单总价
        $order['yijia_heji']     = $result['result']['yijia_heji_s']; //溢价收益
        $order['dai_type']     = 1; //溢价收益
        $order['tag']     = 'app'; //溢价收益

        // 添加订单
        $order_id = M('order')->add($order);
        if($order_id)
            {   
                $koudian = 0;
                foreach($order_goods as $key => $val)
                {
                    $goods = M('goods')->where("goods_id =".$val['goods_id'])->find();

                    if(!empty($goods['fenbu_koudian'])){
                        $goods['fenbu_koudian'] = json_decode($goods['fenbu_koudian'],true);
                        foreach ($goods['fenbu_koudian'] as $kk=>$vv){
                            if($vv['fenbu_id'] == $users_fenbu_id){
                                if(!empty($vv['fenbu_koudian'])){
                                    $goods['points'] = $vv['fenbu_koudian'];
                                    break;
                                }
                            }
                        }
                    }

                    $nyj=yj_price($val['goods_id'],$val['member_goods_price'],$users_fenbu_id);
                    if($val['store_yijia'] != 1){
                        if($nyj < 0){
                            $nyj = 0;
                        }
                    }
                    $val['order_id'] = $order_id;
                    $val['store_id'] = STORE_ID;
                    $val['yijia'] = $nyj;
                    $val['points'] = $goods['points'];
                    $rec_id = M('order_goods')->add($val);
                    $koudian += ($val['member_goods_price'] * ($val['points']/100))*$val['goods_num'];
                    M("order_yijia")->data([
                        'order_sn'=>$order['order_sn'],
                        'order_id'=>$order_id,
                        'goods_id'=>$val['goods_id'],
                        'store_id'=>STORE_ID,
                        'consignee'=>$order['consignee'],
                        'spec_key'=>$val['spec_key'],
                        'goods_num'=>$val['goods_num'],
                        'y_price'=>$val['member_goods_price'],
                        'price'=>$nyj,
                        'fenbu_id'=>$users_fenbu_id,
                        'add_time'=>\time()
                    ])->add(); //写入溢价分成表
                     if(!empty($val['spec_key'])){
                         M('spec_goods_price')->where("goods_id = ".$val['goods_id']." and `key`='".$val['spec_key']."'")->setDec('store_count',(int)$val['goods_num']);
                       
                    }
                    
                     if($val['is_yanzhi'] == 1){
                          M('order_yanzhi')->add([
                          'goods_id'=>$val['goods_id'],
                          'order_id'=>$order_id,
                          'key'=>$val['spec_key'],
                          'price'=>$val['member_goods_price'],
                          'points'=>$val['points'],
                          'yijia'=>$val['yijia'],
                          'goods_num'=>$val['goods_num'],
                          'add_time'=>time()]
                          );
                        }
                     $mygoods.=$val['goods_id'].'|'.$val['goods_num'].'|'.$val['spec_key'].','; //记录产品。
                    if(!$rec_id)
                        $this->error('添加失败');
                }
                M('order')->where(['order_id'=>$order_id])->save(['kou_price'=>$koudian]);
                logOrder($order_id,'您提交了订单，请等待系统确认','提交订单',$order['user_id'],2,$mygoods);   
				if($dai_type=='2'){
					M('order_jian')->where('order_id='.$order_id)->delete();//删除出入库重写写入记录/index.php?m=Seller&c=Order&a=add_order&action=1
					for($i=1;$i<=(int)I('biaoqian');$i++){
						M('order_jian')->add([
							"order_id"=>$order_id,
							"ruku_num"=>$i,
							"chuku_num"=>$i
						]);
					}
                    $data = array('code'=>1,'msg'=>'添加订单成功','data'=>[]);
                    exit(json_encode($data));
//					$this->success('添加订单成功',"/index.php/Seller/Order/biaoqian_print/order_id/".$order_id);
				}else{
                    $data = array('code'=>1,'msg'=>'添加订单成功','data'=>[]);
                    exit(json_encode($data));
//					$this->success('添加订单成功',U("Order/detail",array('order_id'=>$order_id)));
				}
				
                exit();
            }
        else{
            $data = array('code'=>0,'msg'=>'添加失败','data'=>[]);
            exit(json_encode($data));
        }

    }
    /**
     * 生成标签数
     * */
    public function generateLabel(){
        $num = I('num');
        $order_id = I('order_id');
        $order_ids = I('order_ids');

        //单个修改标签数
        if(!empty($order_id)){
            
            if($num>150){
                $data = array('code'=>0,'msg'=>'单个订单标签数上限150个，请包装尽量捆绑一起。','data'=>[]);
                exit(json_encode($data));
            }
           
            $order = M('order')->where('order_id='.$order_id.' and store_id = '.STORE_ID.' and order_status =0')->find();
            
            if($order && $num<=150) {
                $sql= M('order')->where("order_id = $order_id and store_id = ".STORE_ID)->save(array('jian_count'=>$num)); // 根据条件保存修改的数据
              
                M('order_jian')->where('order_id='.$order_id)->delete();//删除出入库重写写入记录
                for($i=1;$i<=(int)$num;$i++){
                    $a = M('order_jian')->add([
                        "order_id"=>$order_id,
                        "ruku_num"=>$i,
                        "chuku_num"=>$i
                    ]);
                   
                }
                 
            }
    
        }
        //批量修改标签数
        if(!empty($order_ids)){
            if($num>150){
                $data = array('code'=>0,'msg'=>'单个订单标签数上限150个，请包装尽量捆绑一起。','data'=>[]);
                exit(json_encode($data));
            }
            $order_ids = explode($order_ids,',');
            foreach ($order_ids as $k=>$v){
                $order = M('order')->where('order_id='.$v.' and store_id = '.STORE_ID.' and order_status =0')->find();
                if($order && $num<=150) {
                    $sql= M('order')->where("order_id = $v and store_id = ".STORE_ID)->save(array('jian_count'=>$num)); // 根据条件保存修改的数据
                    M('order_jian')->where('order_id='.$v)->delete();//删除出入库重写写入记录
                    for($i=1;$i<=(int)$num;$i++){
                        M('order_jian')->add([
                            "order_id"=>$v,
                            "ruku_num"=>$i,
                            "chuku_num"=>$i
                        ]);
                        M('debug')->add([
                            'text' => json_encode([
                                'action' => 'changebiaoqian',
                                'store_id' => STORE_ID,
                                'order_id' => $v,
                            ])
                        ]);
                    }
                }
            }

        }


        $data = array('code'=>1,'msg'=>'更新成功','data'=>[]);
        exit(json_encode($data));
    }

    /**
     * 退货单列表
     * */
    public function returnGoodsList(){

        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
//        $orderLogic = new OrderLogic();
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }

        // 搜索条件
        $condition = array();
        if($begin && $end){
            $condition['tuihuo_time'] = array('between',"$begin,$end");
        }

        I('status')!="" ? $condition['status'] = I('status') : false;
        //I('order_sn') ? $condition['remark'] = array('like','%'.trim(I('order_sn')).'%') : false;
        I('order_sn') && $condition['_string'] = ' (a.order_sn like "%'.I('order_sn').'%")  OR (a.remark like "%'.I('order_sn').'%") ';
        I('consignee') && $condition['_string'] = ' (b.nickname like "%'.I('consignee').'%")  OR (b.company like "%'.I('consignee').'%") ';
        $condition['a.store_id']=STORE_ID;

        $count = M('return_goods a')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->where($condition)->count();

        //获取订单列表
        $orderList = M('return_goods a')
            ->field('a.*,b.*,c.original_img as imgs,c.goods_name,d.key_name')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->join('ty_spec_goods_price d ON a.spec_key=d.key','LEFT')
            ->where($condition)->limit("$showPage,$limit")->order('a.id desc')->select();
        foreach ($orderList as $k=>$v){
            if(!empty($v['imgs'])){
                $orderList[$k]['imgs'] = C('MYOSS')['url2'].$v['imgs'];
            }
            $orderList[$k]['dsprice'] = $v['member_goods_price']*(float)$v['goods_num'];
            $orderList[$k]['ptprice'] = $orderList[$k]['dsprice']*($v['points']/100);
            $orderList[$k]['ptprices'] = $orderList[$k]['dsprice']-$orderList[$k]['ptprice'];
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$orderList,'page'=>I('page'),'limit'=>$count]);
        exit(json_encode($data));
        //echo json_encode($orderList);exit;
//        $store_list = M('store')->getField('store_id,store_name');
//        $this->assign('store_list',$store_list);
//        $this->assign('orderList',$orderList);
//        $this->assign('page',$show);// 赋值分页输出
//        $this->display();
    }

    /**
     * 订单详情
     * */
    public function returnDetail(){
        $id = I('id');
        $where=array();
        if(!empty($id)){
            $where['id']=$id; //如果是修改。
            $orderGoods=M('return_goods a')
                ->field('a.*,b.nickname,b.company,c.store_name,c.store_phone,d.goods_name')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->join('ty_store c on a.store_id=c.store_id','LEFT')
                ->join('ty_goods d on a.goods_id=d.goods_id','LEFT')
                ->where($where)->find();
            $spec=M('spec_goods_price')->where('`key`="'.$orderGoods['spec_key'].'"')->find();
            $orderGoods['guige']=$spec['key_name'];
            $data = array('code'=>1,'msg'=>'获取成功','data'=>$orderGoods);
            exit(json_encode($data));
        }else{
            $data = array('code'=>0,'msg'=>'获取失败','data'=>[]);
            exit(json_encode($data));
        }
        //echo \json_encode($orderGoods);exit;
//        $this->assign('order',$orderGoods);
//        $this->display();
    }


    /**
     * 店铺活动
     * */
    public function promSave(){
        $prom_id = I('id');
        $data = I('post.');
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['goods_key'] = \json_encode($data['goods_key']);
        if(empty($data['start_time']) || empty($data['end_time'])){
            $data = array('code'=>0,'msg'=>'缺少时间','data'=>[]);
            exit(json_encode($data));
        }
        if(empty($data['goods_key'])){
            $data = array('code'=>0,'msg'=>'缺少商品','data'=>[]);
            exit(json_encode($data));
        }
        if(!empty($prom_id)){
            M('prom_goods')->where("id=$prom_id and store_id =".STORE_ID)->save($data);
            $last_id = $prom_id;
            sellerLog("管理员修改了商品促销 ".I('name'));
            cart_price();
             $data = array('code'=>1,'msg'=>'编辑成功','data'=>[]);
            exit(json_encode($data));
        }else{
            $data['store_id'] = $this->store_id;
            $last_id = M('prom_goods')->add($data);
            sellerLog("管理员添加了商品促销 ".I('name'));
            cart_price();
            $data = array('code'=>1,'msg'=>'添加成功','data'=>[]);
            exit(json_encode($data));
        }

        // if(is_array($data['goods_id'])){
        //     $goods_id = implode(',',array_unique($data['goods_id']));
        //     if($prom_id>0){
        //         M("goods")->where("prom_id=$prom_id and prom_type=".$data["type"]." and store_id =".STORE_ID)->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
        //         $data = array('code'=>1,'msg'=>'编辑成功','data'=>[]);
        //         exit(json_encode($data));
        //     }
        //     //M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
        //     if($data['expression']=='100' && $data["type"] == 0){
        //         M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
        //     }else{
        //         M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
        //     }
        // }
        // cart_price();
        // $data = array('code'=>1,'msg'=>'更新成功','data'=>[]);
        // exit(json_encode($data));
    }

    /**
     * 店铺打折
     * */
    public function storeAddPromotion(){

        $id = I('id');

        $info['start_time'] = date('Y-m-d');
        $info['end_time'] = date('Y-m-d',time()+3600*60*24);
        $info = [];
        if(!empty($id)){
            $info = M('store_promotion')
                ->where("id=$id and store_id=".STORE_ID)
                ->find();
            if(empty($info)){
                $data = array('code'=>0,'msg'=>'非法操作！','data'=>[]);
                exit(json_encode($data));
            }
        }
        $info['start_time'] = date('Y-m-d',$info['start_time']);
        $info['end_time'] = date('Y-m-d',$info['end_time']);
            $startTime = strtotime(I('start_time'));
            $endTime = strtotime(I('end_time'));
            if($endTime < $startTime){
                $data = array('code'=>0,'msg'=>'结束时间不能小于开始时间！','data'=>[]);
                exit(json_encode($data));
            }
            if(empty(I('discount'))){
                $data = array('code'=>0,'msg'=>'折扣不能为空！','data'=>[]);
                exit(json_encode($data));
            }
            if(!empty($id)){
                $sql = M('store_promotion')->where(['id'=>$id])->save([
                    'discount'=>I('discount'),
                    'start_time'=>$startTime,
                    'end_time'=>$endTime
                ]);
            }else{
                $sql = M('store_promotion')->add([
                    'discount'=>I('discount'),
                    'start_time'=>$startTime,
                    'end_time'=>$endTime,
                    'addtime'=>time(),
                    'status'=>1,
                    'store_id'=>STORE_ID
                ]);
            }
            if(!empty($sql)){
                $data = array('code'=>1,'msg'=>'操作成功！','data'=>[]);
                exit(json_encode($data));
            }else{
                $data = array('code'=>0,'msg'=>'操作失败！','data'=>[]);
                exit(json_encode($data));
            }

    }

    /**
     * 店铺活动列表
     * */
    public function promGoodsList(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $key = I('key');
        $where = [];
        if(!empty($key)){
            $where['a.name'] = ['like','%'.$key.'%'];
        }
        $showPage = $page*$limit;
//        $parse_type = array('0'=>'单品秒杀','1'=>'降价促销','2'=>'一口价促销','3'=>'买就赠优惠券','4'=>'全店打折');
        $level = M('user_level')->select();
        if($level){
            foreach ($level as $v){
                $lv[$v['level_id']] = $v['level_name'];
            }
        }
//        $this->assign("parse_type",$parse_type);
        $count = M('prom_goods a')
            ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where($where)
            ->where('a.type in (0,1,2,3,4) and a.store_id = '.$this->store_id)
            ->count();
//        $Page  = new \Think\Page($count,10);
//        $show = $Page->show();
        $res = M('prom_goods a')
            ->field('a.*,b.store_name,b.zhekou')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where($where)
            ->where('a.type in (0,1,2,3,4) and a.store_id = '.$this->store_id)
            ->order('a.id desc')
            ->limit($showPage.','.$limit)
            ->select();
        $time = time();
        if($res){
            foreach ($res as $k=>$val){
                if(!empty($val['group']) && !empty($lv)){
                    $val['group'] = explode(',', $val['group']);
                    foreach ($val['group'] as $v){
                        $val['group_name'] .= $lv[$v].',';
                    }
                }
                $val['state'] = empty($val['status']) ? '管理员关闭' : '正常';
                if($val['end_time'] < $time){
                    $val['statuss'] = 3;
                }
                if($val['start_time'] > $time){
                    $val['statuss'] = 1;//未开始
                }
                if($val['start_time'] < $time && $val['end_time'] > $time){
                    $val['statuss'] = 2;//进行中
                }
                $res[$k] = $val;
            }
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$res,'page'=>I('page'),'limit'=>$count]);
        exit(json_encode($data));
//        $this->assign('page',$show);// 赋值分页输出
//        $this->assign('prom_list',$prom_list);
//        $this->display();
    }

    /**
     * 店铺活动详情
     * */
    public function promGoodsInfo()
    {

        $prom_id = I('id');
        if($prom_id>0){
            $info = M('prom_goods')->where("id=$prom_id and store_id=".STORE_ID)->find();
            if(empty($info))
                $this->error('非法操作！');

            $time = time();
            $info['start_time'] = date('Y-m-d',$info['start_time']);
            $info['end_time'] = date('Y-m-d',$info['end_time']);
            if($info['start_time'] > time()){
                $info['statuss'] = 1;//未开始
            }
            if($info['start_time'] > $time && $info['end_time'] > $time){
                $info['statuss'] = 2;//进行中
            }
            if($info['end_time'] < $time){
                $info['statuss'] = 3;//已结束
            }
            if($info['goods_key']){
                $goods_key=\json_decode($info['goods_key']);
                foreach($goods_key as $key=>$v){
                    $prom_goods[$key]= M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
                    $prom_goods[$key]['shop_price']=$prom_goods[$key]['price'];
                }

            }else{
                $prom_goods = M('goods')->where("prom_id=$prom_id and store_id=".STORE_ID)->select();
            }

            $info['prom_goods'] = $prom_goods;
            $data = array('code'=>1,'msg'=>'获取成功！','data'=>$info);
            exit(json_encode($data));
        }else{
            $data = array('code'=>0,'msg'=>'获取失败！','data'=>[]);
            exit(json_encode($data));
        }

    }

    /**
     * 店铺打折列表
     * */
    public function storePromotion(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }

        $showPage = $page*$limit;
        $count = M('store_promotion a')
            ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where("a.store_id=".STORE_ID)
            ->count();

        $res = M('store_promotion a')
            ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where("a.store_id=".STORE_ID)
            ->order('a.id desc')
            ->limit($showPage.','.$limit)
            ->select();
        $time = time();
        if($res){
            foreach ($res as $k=>$v){
                if($res[$k]['status'] == 1){
                    $res[$k]['state'] = '未审核';
                }else{
                    $res[$k]['state'] = '已审核';
                }
                if($v['end_time']<$time){
                    $res[$k]['statuss'] = 3;
                }
                if($v['start_time'] > time()){
                    $res[$k]['statuss'] = 1;//未开始
                }
                if($v['start_time'] < $time && $v['end_time'] > $time){
                    $res[$k]['statuss'] = 2;//进行中
                }
            }
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$res,'page'=>I('page'),'limit'=>$count]);
        exit(json_encode($data));
    }

    /**
     * 打折店铺详情
     * */
    public function storePromotionDetail(){
        $id = I('id');
        if(empty($id)){
            $data = array('code'=>0,'msg'=>'获取失败','data'=>[]);
            exit(json_encode($data));
        }
        $info = M('store_promotion')
            ->where("id=$id and store_id=".STORE_ID)
            ->find();

        if(!empty($info)){
            $info['start_time'] = date('Y-m-d',$info['start_time']);
            $info['end_time'] = date('Y-m-d',$info['end_time']);
            $data = array('code'=>1,'msg'=>'获取失败','data'=>$info);
        }else{
            $data = array('code'=>0,'msg'=>'获取失败','data'=>[]);
        }
        exit(json_encode($data));
    }


    /**
     * 每日秒杀列表
     * */
    public function  dailyGoodsList(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
        $key = I('key');
        $where = [];
        if(!empty($key)){
            $where['a.name'] = ['like','%'.$key.'%'];
        }
        $count = M('prom_goods a')
            ->field('a.*,b.store_name')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where($where)
            ->where('a.type = 5 and a.store_id = '.$this->store_id)
            ->count();
        $res = M('prom_goods a')
            ->field('a.*,b.store_name,b.zhekou')
            ->join('ty_store b on a.store_id=b.store_id','LEFT')
            ->where($where)
            ->where('a.type = 5 and a.store_id = '.$this->store_id)
            ->order('a.id desc')
            ->limit($showPage.','.$limit)
            ->select();
        $time = time();
        if($res){
            foreach ($res as $k=>$val){
                if(!empty($val['group']) && !empty($lv)){
                    $val['group'] = explode(',', $val['group']);
                    foreach ($val['group'] as $v){
                        $val['group_name'] .= $lv[$v].',';
                    }
                }

                $val['state'] = empty($val['status']) ? '管理员关闭' : '正常';
                if(intval($val['end_time']) < $time){
                    $val['state'] = '已结束';
                    $val['statuss'] = 3;
                }
                if(intval($val['start_time']) > $time){
                    $val['statuss'] = 1;//未开始
                }
                if(intval($val['start_time']) < $time && intval($val['end_time']) > $time){
                    $val['statuss'] = 2;//进行中
                }
                $res[$k] = $val;
            }
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$res,'page'=>I('page'),'limit'=>$count]);
        exit(json_encode($data));
    }

    /**
     * 每日秒杀详情
     * */
    public function dailyGoodsInfo(){

        $prom_id = I('id');
        if($prom_id>0){
            $info = M('prom_goods')->where("id=$prom_id and store_id=".STORE_ID)->find();
            if(empty($info)){
                $data = array('code'=>0,'msg'=>'非法操作','data'=>[]);
                exit(json_encode($data));
            }

            $info['start_time'] = date('Y-m-d',$info['start_time']);
            $info['end_time'] = date('Y-m-d',$info['end_time']);
            if($info['goods_key']){
                $goods_key=\json_decode($info['goods_key']);
                foreach($goods_key as $key=>$v){
                    $prom_goods[$key]= M('spec_goods_price a')->field('a.key,a.key_name,a.price,b.*')->join('ty_goods b on a.goods_id=b.goods_id','LEFT')->where('a.key="'.$v.'"')->find();
                    $prom_goods[$key]['shop_price']=$prom_goods[$key]['price'];
                }
            }else{
                $prom_goods = M('goods')->where("prom_id=$prom_id and store_id=".STORE_ID)->select();
            }
            $info['prom_goods'] = $prom_goods;
            $data = array('code'=>1,'msg'=>'获取成功','data'=>$info);
        }else{
            $data = array('code'=>0,'msg'=>'获取失败','data'=>[]);
        }
        exit(json_encode($data));
    }

    /**
     * 每日秒杀编辑/添加
     * */
    public function dailyGoodsSave(){

        $prom_id = I('id');
        $data = I('post.');
//        $data['start_time'] = strtotime($data['start_time']);
//        $data['end_time'] = strtotime($data['end_time']);

        $time = $data['times'];
        $data['start_time'] = strtotime($time);
        $data['end_time'] = $data['start_time']+86399;
        $data['group'] = implode(',', $data['group']);
        $data['prom_code'] = $data['prom_code'];
        //只允许一件商品
        $length = 0;
        if(!empty($data['goods_id'])){
            $goodsID = array_unique($data['goods_id']);
            $length = count($goodsID,COUNT_NORMAL);
            if($length>3){
                // $this->error('每日秒杀只能选择三个个商品多个规格');
                $data = array('code'=>0,'msg'=>'每日秒杀只能选择三个个商品多个规格','data'=>[]);
                exit(json_encode($data));
            }

        }
        $data['goods_key'] = \json_encode($data['goods_key']);
         
        if($prom_id){
            
            $promData = M('prom_goods')->where(['id'=>$prom_id])->find();//获取要修改的活动
            
             $prom = M('prom_goods')->where('start_time = '.$data['start_time'].' and end_time = '.$data['end_time'])->where(['type'=>5,'store_id'=>$this->store_id])->find();//找到同一天有数据可以修改商品不可以修改为同一天日期
             if(!empty($prom)){
                 //如果已经存在这个日期的每日秒杀，
                 if($prom['id'] != $prom_id){
                     if($data['start_time'] == $prom['start_time']){
                          $data = array('code'=>0,'msg'=>'不可编辑多条同一天','data'=>[]);
                         exit(json_encode($data));
                        //   $this->error('不可编辑多条同一天');
                     }
                 }
             }
            
            M('prom_goods')->where("id=$prom_id and store_id =".STORE_ID)->save($data);
            $last_id = $prom_id;
            sellerLog("管理员修改了商品促销 ".I('name'));
        }else{
            $data['store_id'] = $this->store_id;
            //查询商家是否有这一天秒杀
            $prom = M('prom_goods')->where('start_time = '.$data['start_time'].' and end_time = '.$data['end_time'])->where(['type'=>5,'store_id'=>$this->store_id])->find();
            
            if(!empty($prom)){
                $data = array('code'=>0,'msg'=>'当天已经有秒杀','data'=>[]);
                exit(json_encode($data));
//                $this->error('当天已经有秒杀');
            }
            $last_id = M('prom_goods')->add($data);
            sellerLog("管理员添加了商品促销 ".I('name'));
        }
      
        if(is_array($data['goods_id'])){
            $goods_id = implode(',',array_unique($data['goods_id']));
            if($prom_id>0){
                M("goods")->where("prom_id=$prom_id and prom_type=".$data["type"]." and store_id =".STORE_ID)->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
            }
            //M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
            if($data['expression']=='100'){
                M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
            }else{
                M("goods")->where("goods_id in($goods_id)")->save(array('prom_id'=>$last_id,'prom_type'=>$data['type'],'zd'=>0));
            }
        }
        cart_price();
        $data = array('code'=>1,'msg'=>'编辑每日秒杀成功','data'=>[]);
        exit(json_encode($data));
//        $this->success('编辑每日秒杀成功',U('Promotion/daily_goods_list'));
    }


    /**
     * 删除活动
     * */
    public function promGoodsDel(){
        $prom_id = I('id');
        $prom_goods = M('prom_goods')->where("id=$prom_id and store_id=".STORE_ID)->find();
        if($prom_goods['zd']==1){
            $data = array('code'=>0,'msg'=>'全店折扣活动不能删除','data'=>[]);
            exit(json_encode($data));
        }
        if($prom_goods['end_time']>time())
        {
            $data = array('code'=>0,'msg'=>'该活动时间未结束不能删除','data'=>[]);
            exit(json_encode($data));
        }
        M("goods")->where("prom_id=$prom_id and store_id = {$this->store_id}")->save(array('prom_id'=>0,'prom_type'=>0,'zd'=>0));
        M('prom_goods')->where("id=$prom_id and store_id = {$this->store_id}")->delete();
        $data = array('code'=>1,'msg'=>'删除活动成功','data'=>[]);
        exit(json_encode($data));

    }
        
        
    /**
    *删除全店打折
    */
       public function prom_store_del()
    {
        
        $prom_id = I('id');
        $prom_goods = M('store_promotion')->where("id = $prom_id")->find();

        if($prom_goods['end_time']>time())
        {
              $data = array('code'=>0,'msg'=>'该活动时间未结束不能删除','data'=>[]);
            exit(json_encode($data));
        }
        M('store_promotion')->where("id=$prom_id and store_id = {$this->store_id}")->delete();
        $data = array('code'=>1,'msg'=>'删除成功','data'=>[]);
        exit(json_encode($data));
    }
        
    /**
     * 店铺信息修改
     * */
    public function save_store_info(){
        // $data['store_phone'] = I('store_phone');
        // $data['store_banner'] = I('store_banner');
        // $data['store_logo'] = I('store_logo');
        $getdata = [];
        if(!empty(I('store_zy'))){
            $getdata['store_zy'] = I('store_zy');
        }
        if(!empty(I('store_phone'))){
            $getdata['store_phone'] = I('store_phone');
        }
        if(!empty(I('store_banner'))){
            $getdata['store_slide'] = I('store_banner');
        }
        if(!empty(I('store_logo'))){
            $getdata['store_logo'] = I('store_logo');
        }
        if(!empty(I('store_slide_url'))){
            $getdata['store_slide_url'] = I('store_slide_url');
        }
        
        $store_id = STORE_ID;
        $store = M('store')->where(['store_id'=>$store_id])->find();
  
        if(!empty($store)){
            $sql = M('store')->where(['store_id'=>$store_id])->save($getdata);
                $data = array('code'=>1,'msg'=>'修改成功','data'=>$getdata);
                exit(json_encode($data));
        }else{
            $data = array('code'=>0,'msg'=>'信息错误','data'=>[]);
            exit(json_encode($data));
        }
    }

    /**
     * 获取店铺信息
     * */
    public function storeInfo(){
        $store = M('store')->where(['store_id'=>STORE_ID])->find();
        if(!empty($store['store_logo'])){
            $store['store_logo'] = C('MYOSS')['url2'].$store['store_logo'];
        }
        if(!empty($store['store_slide'])){
            $store['store_slide'] = C('MYOSS')['url2'].$store['store_slide'];
        }

        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$store);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 公共上传图片
     * */
    public function upImg(){
    //   saveImg($data);
    //   var_dump($_FILES);
    //   var_dump(I(''));
    //   die;
    $data = I('');
    $img['name'] = $data['upload']['postname'];
    $img['tmp_name'] = $data['upload']['name'];
    $img['type'] = $data['upload']['mime'];

        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728 ;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->savePath = './Public/upload/Appimg';//保存的路径
        $upload->rootPath = './'; // 设置附件上传根目录  必须设置
                    // dump($upload->savePath);exit;
        // 上传单个文件
        $info = $upload->uploadOne($img);
                // dump($info);exit;
        if(!$info) {// 上传错误提示错误信息
            // $this->error($upload->getError());
            dump($upload->getError());
        }else{// 上传成功 获取上传文件信息
    //                    dump($info);exit;
            $data['thumb'] = $_SERVER['HTTP_HOST'].$info['savepath'].$info['savename'];
            return $data;
        }
        $data = array('code'=>1,'msg'=>'上传图片','data'=>$data);
        exit(json_encode($data));
    }

    /**
     * 结算列表
     * */
    public function withdrawals(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;

        $model = M("store_withdrawals");
        $status = I('status');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        $create_time = I('create_time');
        $create_time = str_replace("~","-",$create_time);
        $create_time = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 year')).' - '.date('Y-m-d',strtotime('+1 day'));
        $create_time2 = explode(' - ',$create_time);
        $where = "store_id = ".STORE_ID." and create_time >= '".strtotime($create_time2[0])."' and create_time <= '".strtotime($create_time2[1])."' ";

        if($status === '0' || $status > 0)
            $where .= " and status = $status ";
        $account_bank && $where .= " and account_bank like '%$account_bank%' ";
        $account_name && $where .= " and account_name like '%$account_name%' ";

        $count = $model->where($where)->select();
        //计算合计金额
        $hejiprice=$tuihuo_heji=0;
        foreach($count as $v){
            $tuihuo_heji+=$v['th_money'];
            $hejiprice+=$v['money'];
        }
        $list = $model->where($where)->order("`id` desc")->limit($showPage,$limit)->select();

        foreach ($list as $k=>$v){
            $v['shouxufei'] = sanwei($v['yf_money']*0);
            $v['yf_money2'] = sanwei($v['yf_money']-$v['shouxufei']);
            $list[$k]=$v;
        }

        $store = M('store')->where("store_id = ".STORE_ID)->find();

        $tuihuo_list=M('return_goods a')
            ->field('a.*,b.goods_name,b.original_img')
            ->join('ty_goods b on a.goods_id=b.goods_id','LEFT')
            ->where('a.store_id='.STORE_ID.' and status=0')->select();
        $tuihuo=0;//echo \json_encode($tuihuo_list);
        foreach($tuihuo_list as $v){
            $tuihuo+=$v['member_goods_price']*$v['goods_num']*((100-$v['points'])/100);
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$list,'page'=>$page,'limit'=>count($count),'hejiprice'=>geshi($hejiprice),'tuihuo_heji'=>geshi($tuihuo_heji),'shouxufei'=>sanwei(($store['store_money']-$tuihuo)*0),'store'=>$store,'tuihuo'=>geshi($tuihuo)]);
        exit(json_encode($data));
    }

    /**
     * 结算金额明细列表
     * */
    public function orderWithdrawal(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
        $id= I('id');
        $order_sn= I('order_sn');
        $model = M("order_statis a");
        $where = "a.store_id = ".STORE_ID." and a.withdrawals_id=".$id;
        if($order_sn){
            $where .= " and a.order_sn like '%".$order_sn."%'";
        }
      
        $count = $model
            ->field('a.*,b.total_amount,b.add_time,b.order_amount')
            ->join('ty_order b on a.order_sn=b.order_sn','LEFT')
            ->where($where)->select();
      
        //计算合计金额
        $dan_heji=$shi_heji=$kou_heji=$yin_heji=$cps_heji=0;
        foreach($count as $v){
            $dan_heji+=$v['total_amount'];
            $shi_heji+=$v['order_totals'];
            $kou_heji+=$v['commis_totals'];
            $yin_heji+=$v['result_totals'];
            $cps_heji+=$v['cps_price'];
        }
        $list = $model
            ->field("a.*,b.order_id,b.order_amount,b.total_amount,d.company,CONCAT(biaoshi_xian,if(d.fast_flag='1','快','')) as biaoshi_xian,e.ruku_time")
            ->join('ty_order b on a.order_sn=b.order_sn','LEFT')
            ->join('ty_users d on b.user_id=d.user_id')
            ->join('ty_order_jian e on b.order_id=e.order_id')
            ->where($where)->order("e.ruku_time asc")->group('b.order_sn')
            ->limit($showPage.','.$limit)->select();
        foreach ($list as $k=>$v){
            $list[$k]['cps_price'] = 0;
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$list,'page'=>$page,'limit'=>count($count),'dan_heji'=>$dan_heji,'shi_heji'=>geshi($shi_heji),'kou_heji'=>geshi($kou_heji),'yin_heji'=>geshi($yin_heji),'cps_heji'=>geshi($cps_heji)]);
        exit(json_encode($data));
    }
    /**
     * 退货金额明细列表
     * */
    public function tuihuoOrderWithdrawal(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
        $id= I('id');
        $order_sn= I('order_sn');
        $goods_name= I('goods_name');
        $where = "a.store_id = ".STORE_ID." and a.withdrawals_id=".$id;
        if($goods_name){
            $where .= " and (a.remark like '%".$goods_name."%' or order_sn like '%".$goods_name."%')";
        }
        if($order_sn){
            $where .= " and a.order_sn like '%".$order_sn."%'";
        }
        $count =M("return_goods a")
            ->field('a.*,b.*,c.goods_name,c.original_img')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->where($where)->select();
        //计算合计金额
        $dsprice=$kou_heji=$yin_heji=$dan_heji=0;
        foreach($count as $v){
            $dsprice=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
            $dan_heji+=$dsprice;
            $kou_heji+=$dsprice*($v['points']/100); //平台价
            $yin_heji+=$dsprice-($dsprice*($v['points']/100));
        }
        $list =M("return_goods a")
            ->field('a.*,b.*,c.goods_name,c.original_img')
            ->join('ty_users b ON a.user_id = b.user_id','LEFT')
            ->join('ty_goods c ON a.goods_id = c.goods_id','LEFT')
            ->where($where)->order("`id` desc")->limit($showPage.','.$limit)->select();
        foreach($list as $key=>$v){
            $list[$key]['dsprice']=(float)$v['member_goods_price']*(float)$v['goods_num']; //订单价
            $list[$key]['ptprice']=$list[$key]['dsprice']*($v['points']/100); //平台价
            $list[$key]['ptprices']=$list[$key]['dsprice']-$list[$key]['ptprice'];
            // $heji_ptprice+=$ptprice;
            // $heji_ptprices+=$ptprices;
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$list,'page'=>$page,'limit'=>count($count),'dan_heji'=>geshi($dan_heji),'kou_heji'=>geshi($kou_heji),'yin_heji'=>geshi($yin_heji)]);
        exit(json_encode($data));
    }

    /**
     * 待结算订单
     * */
    public function order_statis_djiesuan(){
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }
        $showPage = $page*$limit;
        $order_sn= I('order_sn');
        $create_date = I('create_date');
        $create_date = str_replace("+"," ",$create_date);
        $create_date2 = $create_date  ? $create_date  : date('Y-m-d',strtotime('-1 month')).' 00:00 - '.date('Y-m-d',strtotime('+1 month')).' 23:59';
        $create_date3 = explode(' - ',$create_date2);
        $create_date4=($create_date3[0]==$create_date3[1]) ? strtotime($create_date3[1])+86399 :strtotime($create_date3[1]);

        $where = "a.store_id = ".STORE_ID." and (d.withdrawals_id=0 or d.withdrawals_id is null) and c.status_r=1 and c.ruku_time >= '".strtotime($create_date3[0])."' and c.ruku_time <= '".$create_date4."' ";
        if($order_sn){
            $where .= " and a.order_sn like '%".$order_sn."%'";
        }

        $count = M()->query("SELECT a.order_id,a.order_sn,a.order_status,a.order_amount,a.total_amount,a.dai_type,a.cps_price,
		(SELECT sum(b.goods_num*b.member_goods_price*b.points/100) from ty_order_goods b where b.order_id=a.order_id) as commis_totals,
		(SELECT (a.order_amount*b.points/100) from ty_order_goods b where b.order_id=a.order_id limit 1) as commis_totals_k,
		c.status_r,c.ruku_time,d.order_totals
		 from ty_order a 
		 INNER JOIN ty_order_jian c on a.order_id=c.order_id 
		 LEFT JOIN ty_order_statis d on a.order_sn=d.order_sn 
		 where $where group by a.order_sn");

        //计算合计金额
        $dan_heji=$kou_heji=$yin_heji=$shi_heji=$cps_heji=0;
        foreach($count as $v){
            if($v['dai_type']==2){
                $kou_heji+=$v['commis_totals_k']; //$dan_heji+=0;
            }else{
                $kou_heji+=$v['commis_totals']; //
                $cps_heji+=$v['cps_price']; //
            }

            if($v['order_totals'] && $v['total_amount']!=$v['order_totals'])
                $shi_heji+=$v['order_totals'];
            else
                $shi_heji+=$v['total_amount'];

            $dan_heji+=$v['total_amount'];
        }

        $yin_heji=$shi_heji-$kou_heji-$cps_heji;

        $list = M()->query("SELECT a.order_id,a.admin_note,a.order_sn,a.order_status,a.order_amount,a.total_amount,a.dai_type,a.cps_price,
		(SELECT sum(b.goods_num*b.member_goods_price*b.points/100) from ty_order_goods b where b.order_id=a.order_id) as commis_totals,
		(SELECT (a.order_amount*b.points/100) from ty_order_goods b where b.order_id=a.order_id limit 1) as commis_totals_k,
		c.status_r,c.ruku_time,d.order_totals
		 from ty_order a 
		 INNER JOIN ty_order_jian c on a.order_id=c.order_id 
		 LEFT JOIN ty_order_statis d on a.order_sn=d.order_sn 
		 where $where group by a.order_sn ORDER BY a.order_id desc limit $showPage,$limit");

        foreach($list as $key=>$v){
            $list[$key]['commis_totals']=$v['dai_type']==2 ? $v['commis_totals_k'] : $v['commis_totals'];

            if($v['order_totals'] && $v['total_amount']!=$v['order_totals']){
                $list[$key]['yingshou']=$v['order_totals']-$list[$key]['commis_totals']-$v['cps_price'];
            }else{
                $list[$key]['yingshou']=$v['total_amount']-$v['commis_totals']-$v['cps_price'];
                $list[$key]['order_totals']=$v['total_amount'];
            }
        }
        $order_status = C('ORDER_STATUS');
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$list,'page'=>$page,'limit'=>count($count),'dan_heji'=>geshi($dan_heji),'kou_heji'=>geshi($kou_heji),'yin_heji'=>geshi($yin_heji),'shi_heji'=>geshi($shi_heji),'cps_heji'=>geshi($cps_heji),'order_status'=>$order_status]);
        exit(json_encode($data));
    }


    /**
     * 商品列表
     * */
    public function AppGoodsList(){
        $orderby1 = I('orderby1');
        $orderby2 = I('orderby2');
        $page = I('page',1);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $limit = I('limit',20);
        $showPage = $page*$limit;
        $where = "store_id = ".STORE_ID; // 搜索条件
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;
        (I('store_cat_id1') !== '') && $where = "$where and store_cat_id1 = ".I('store_cat_id1');
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale');
        $goods_state = I('goods_state'); // 商品状态  0待审核 1审核通过 2审核失败  3违规下架
        ($goods_state !== '') && $where = "$where and goods_state in ($goods_state) ";
        //tianxin100  新增商品回收站功能
        $is_delete =  I('is_delete'); // 商品状态  0待审核 1审核通过 2审核失败  3违规下架
        if($is_delete){
            $where = "$where and is_delete = $is_delete ";
        }else{

            $where = "$where and is_delete = 0 ";
        }
        //tianxin100  新增商品回收站功能
        // 关键词搜索
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        $where .= " and is_pint = 0 ";
        $model = M('Goods');
        $count = $model->where($where)->count();
        $order_str = "`{$orderby1}` {$orderby2}";
        $now=\time();

        $goodsList = $model->where($where)->order($order_str)->limit($showPage.','.$limit)->select();
        foreach($goodsList as $key=>$v){
            $goodsList[$key]['kucun']=M('spec_goods_price')->where('goods_id='.$v['goods_id'])->order('store_count asc')->getField('store_count');
            $goodsList[$key]['zhuangtai']=M('store_msg')->where('goods_id='.$v['goods_id'])->order('sm_id desc')->getField('content');

            $huodong='';
            if($v['prom_id']>0){
                $hd=\M('prom_goods')->field('type,expression')->where("end_time>$now and start_time<$now and id=".$v['prom_id'])->find();
                if($hd)
                    $huodong=huodong_name($hd['type'],$hd['expression']);
            }
            $goodsList[$key]["huodong"]=$huodong;
            $goodsList[$key]['original_img'] = C('MYOSS')['url2'].$v['original_img'];
            //重写排序
            $pd_max=M('spec_item')->where("store_id = ".STORE_ID." and goods_id =".$v['goods_id'])->max('sort');
            if($pd_max==0){
                $order_sort=M('spec_item')->field('id,goods_id')->where("store_id = ".STORE_ID." and goods_id =".$v['goods_id'])->order('id asc')->select();
                $ii=0;
                foreach($order_sort as $vs){
                    M('spec_item')->where("id = ".$vs['id']." and goods_id =".$vs['goods_id'])->setField('sort',$ii);
                    $ii++;
                }
            }
            if($v['cat_id3']){
                $cat = M('goods_category')->where(['id'=>$v['cat_id3']])->find();
                $goodsList[$key]["catname"] = $cat['name'];
            }else{
                $goodsList[$key]["catname"] = '';
            }
        }
        $data = array('code'=>1,'msg'=>'获取成功','data'=>['list'=>$goodsList,'page'=>I('page'),'limit'=>$count]);
        exit(json_encode($data));
    }
    

	/*
	 ajax 修改指定表数据字段  一般修改状态 比如 是否推荐 是否开启 等 图标切换的
	 table,id_name,id_value,field,value
	*/ 
    public function changeTableVal(){
        $table = I('table'); // 表名
        $id_name = I('id_name'); // 表主键id名
        $id_value = I('id_value'); // 表主键id值
        $field  = I('field'); // 修改哪个字段
        $value  = I('value'); // 修改字段值
		if($field=="is_on_sale"&&$value==1){
			//如果是修改上下架，判断商品是否在审核中，未审核的不能上架 20181130  tianxin100
			$goods_state = M($table)->where("$id_name = $id_value and store_id = ".STORE_ID)->getField('goods_state'); // 找到这个分类对应的type_id
			if($goods_state ==1){
				M($table)->where("$id_name = $id_value and store_id = ".STORE_ID)->save(array($field=>$value)); // 根据条件保存修改的数据
			}else{
                $data = array('code'=>0,'msg'=>'未审核商品不能上架','data'=>[]);
                exit(json_encode($data));
            }
			
		}else{
			
			M($table)->where("$id_name = $id_value and store_id = ".STORE_ID)->save(array($field=>$value)); // 根据条件保存修改的数据
		}
        $data = array('code'=>1,'msg'=>'修改成功','data'=>[]);
        exit(json_encode($data));
    }
            /*
     * 处理商品恢复
     * */
    public function rollBack(){
        $goods_id = I('goods_id');
        M("goods")->where(" goods_id = ".$goods_id)->save(array("is_delete" =>0));
        $return_arr = array('code' => 1,'msg' => '恢复成功','data'  =>[],);
        $this->ajaxReturn($return_arr);
    }
 
    /**
     * 删除商品
     */
    public function delGoods()
    {
        
        $goods_id = I('goods_id');
        // $error = '';		
        // $value= I('value');      
		M("goods")->where(" goods_id = ".$goods_id)->save(array("is_delete" =>1,"is_on_sale"=>0));		
        $return_arr = array('code' => 1,'msg' => '加入回收站成功','data'  =>[]);        
        $this->ajaxReturn($return_arr);		
        
        
        
        // $goods_id = I('goods_id'); // 表名
        // $error = '';
        
        // // 判断此商品是否有订单
        // $c1 = M('OrderGoods')->where("goods_id = $goods_id")->count('1');
        // $c1 && $error .= '此商品有订单,不得删除! <br/>';
        
        
        //  // 商品团购
        // $c1 = M('group_buy')->where("goods_id = $goods_id")->count('1');
        // $c1 && $error .= '此商品有团购,不得删除! <br/>';   
        
        //  // 商品退货记录
        // $c1 = M('return_goods')->where("goods_id = $goods_id")->count('1');
        // $c1 && $error .= '此商品有退货记录,不得删除! <br/>';
        
        // if($error)
        // {
        //     $return_arr = array('code' => -1,'msg' =>$error,'data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        //     $this->ajaxReturn($return_arr);            
        // }
        
        // // 删除此商品        
        // $result = M("Goods")->where("goods_id = $goods_id and store_id = ".STORE_ID)->delete();  //商品表
        // if($result)
        // {
        //     M("cart")->where('goods_id ='.$goods_id)->delete();  // 购物车
        //     M("comment")->where('goods_id ='.$goods_id)->delete();  //商品评论
        //     M("goods_consult")->where('goods_id ='.$goods_id)->delete();  //商品咨询
        //     M("goods_images")->where('goods_id ='.$goods_id)->delete();  //商品相册
        //     M("spec_goods_price")->where('goods_id ='.$goods_id)->delete();  //商品规格
        //     M("spec_image")->where('goods_id ='.$goods_id)->delete();  //商品规格图片
        //     M("goods_attr")->where('goods_id ='.$goods_id)->delete();  //商品属性     
        //     M("goods_collect")->where('goods_id ='.$goods_id)->delete();  //商品收藏          
        // }            
        // $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>'',);
        // $this->ajaxReturn($return_arr);
    }

    /**
     * 获取一级分类
     * */
    public function primaryClassification(){
        //获取一级分类
        $goods_category = M('goods_category')->where(['level'=>1])->select();
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$goods_category,);
        $this->ajaxReturn($return_arr);

    }
    /**
     * 获取二级分类
     * */
    public function primaryClassificationTWO(){
        $parent_id = I('parent_id');
        $where = [];
        if(!empty($parent_id)){
            $where['parent_id'] = $parent_id;
        }
        $where['level'] = 2;
        //获取一级分类
        $goods_category = M('goods_category')->where($where)->select();
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$goods_category,);
        $this->ajaxReturn($return_arr);

    }
    /**
     * 获取平台三级分类
     * */
    public function primaryClassificationThree(){
        $parent_id = I('parent_id');
        $where = [];
        if(!empty($parent_id)){
            $where['parent_id'] = $parent_id;
        }
        $where['level'] = 3;
        //获取一级分类
        $goods_category = M('goods_category')->where($where)->select();
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$goods_category,);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 获取分类下的品牌
     * */
    public function get_brandList(){
        $parent_id = I('parent_id',0); // 商品分类 父id
        $GoodsLogic = new GoodsLogic();
        $brandList = $GoodsLogic->getSortBrands($parent_id);
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$brandList,);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 获取商家商品分类
     * */
    public function shopCategory(){
        $catListLast = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select();
        foreach ($catListLast as $k=>$v){
            if(!empty($v['image'])){
                $catListLast[$k]['image'] = C('MYOSS')['url2'].$v['image'];
            }
        }
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$catListLast,);
        $this->ajaxReturn($return_arr);
    }


    /**
     * 获取商家商品分类
     * */
    public function shopCategory2(){
        $parent_id = I('parent_id');
        $catListLast = M('store_goods_class')->where("parent_id = ".$parent_id." and store_id = ".STORE_ID)->select();
        foreach ($catListLast as $k=>$v){
            if(!empty($v['image'])){
                $catListLast[$k]['image'] = C('MYOSS')['url2'].$v['image'];
            }
        }
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$catListLast,);
        $this->ajaxReturn($return_arr);
    }
    /**
     * 修改商家分类
     * */
    public function saveShopCategory(){
        $data = I('');
        if(empty($data['cat_id'])){
            $data['store_id'] = STORE_ID;
            $r = M('store_goods_class')->add($data);
        }else{
            $r = M('store_goods_class')->where('cat_id='.$data['cat_id'])->save($data);
        }
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>[]);
        $this->ajaxReturn($return_arr);
    }
    /**
     * 删除商家分类
     * */
    public function delShopCategory(){
        $data = I('');
        M('store_goods_class')->where('cat_id='.$data['cat_id'].' or parent_id='.$data['cat_id'])->delete();
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>[]);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 添加商品/编辑商品
     * */
    public function addEditGoods(){
        $GoodsLogic = new GoodsLogic();
		$basic=tpCache("basic");
        $Goods = D('Admin/Goods');
        $goods_id = I('goods_id',0);
        $type = $goods_id > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        if($goods_id > 0)
        {
            $c = M('goods')->where("goods_id = $goods_id and store_id = ".STORE_ID)->count(); // 如果为修改查看有多少个商品
            if($c == 0)
                $this->error("非法操作",U('Goods/goodsList'));
        }
        //ajax提交验证
        if(IS_POST)
        {
            C('TOKEN_ON',false);  // 是否开启令牌验证
            if(!$Goods->create(NULL,$type))// 根据表单提交的POST数据创建数据对象
            {
                //  提交的数据为空时执行的if 
                $error = $Goods->getError();
                $error_msg = array_values($error);
                $return_arr = array(
                    'status' => -1,
                    'msg' => $error_msg[0],
                    'data' => $error,
                );
                $this->ajaxReturn(json_encode($return_arr));
            }else {
                try {
                    M()->startTrans();
                    $Goods->on_time = time(); // 上架时间
                    $cat_id3 = I('cat_id3',0);
                    $_POST['extend_cat_id_2'] && ($Goods->extend_cat_id = I('extend_cat_id_2'));
                    $_POST['extend_cat_id_3'] && ($Goods->extend_cat_id = I('extend_cat_id_3'));
                    $Goods->shipping_area_ids = implode(',',$_POST['shipping_area_ids']);
                    $Goods->shipping_area_ids = $Goods->shipping_area_ids ? $Goods->shipping_area_ids : '';

                    $store_info = M('store')->where(array('store_id'=>STORE_ID))->find();
                    $myitem = I('item'); //处理默认价格
                    $myitem=array_slice($myitem,0,1);
                    $myitem=array_shift($myitem);

                    $Goods->cost_price = 0;
                    $Goods->shop_price=$myitem['price'];
//                    $Goods->goods_type = $type_id ? $type_id : 0;
                    $Goods->store_id = STORE_ID; // 店家id

                    $goods_limit = M('store_grade')->where(array('sg_id'=>$store_info['grade_id']))->getField('sg_goods_limit');

                    $goods_all_number=M('goods')->where(array('store_id'=>STORE_ID))->count();
                    if(!empty($goods_limit)){

                        if($goods_limit<$goods_all_number){

                            $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '超过上传数量，最多可传商品数量为：'.$goods_limit,'data'  =>'')));
                        }
                    }

                    if($Goods->distribut > ($Goods->shop_price / 2))
                        $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '分销的分成金额不得超过商品金额的50%','data'  =>'')));
                    $Goods->fenbu_id = \session('fenbu_ids');

                    if ($type == 2)
                    {
                        $old_goods_name = M('goods')->field('goods_name,keywords,original_img')->where(['goods_id'=>$goods_id])->find(); //获取旧产品名称

                        if(I('goods_name') != $old_goods_name['goods_name'] ){
                            $Goods->goods_state = 0;
                        }
                        //$Goods->goods_state =1; //修改不用审核
                        //$Goods->is_on_sale = 1;
                        if(empty($_POST['myitems'])){
                            $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '商品规格不能为空','data'  =>'')));
                        }
                        $old_goods_name = M('goods')->field('goods_name,keywords,original_img')->where(['goods_id'=>$goods_id])->find(); //获取旧产品名称
                        if( I('keywords') != $old_goods_name['keywords'] || I('original_img') != $old_goods_name['original_img']){
                            $Goods->goods_state = 0;
                        }
                        
                        if(M('Goods')->where(array('goods_id'=>$goods_id,'store_id'=>STORE_ID))->count()>0){
                            // 修改商品后购物车的商品价格也修改一下
                            $Goods->save(); // 编辑数据到数据库

                            $spec_item = M('spec_item a')->join('ty_spec w ON a.spec_id = w.id')->where(array('a.goods_id'=>$goods_id,'a.store_id'=>STORE_ID))->select();
                            if($spec_item){
                                if(M('goods_type')->where(array('id'=>$spec_item[0]['goods_type_id']))->count()<=0){
                                    $c_data['id'] = $spec_item[0]['goods_type_id'];
                                    $c_data['name'] = '类型';
                                    $c_data['store_id'] = STORE_ID;
                                    M('goods_type')->add($c_data);
                                    unset($c_data);
                                }
                            }
                        }else{
                            $this->ajaxReturn(array('status' => -1,'msg'=> '非法操作'),'JSON');
                        }
                        //$tiaozhuan=U('Goods/goodsList',array('goods_state'=>1,'is_back'=>1));
                        $tiaozhuan='/index.php/Seller/Goods/addEditGoods/goods_id/'.$goods_id;
                    }
                    else
                    {
                        $Goods->yijia_quyu = $store_info['yijia_quyu'];
                        if(empty($store_info['sale_num'])){
                            $store_info['sale_num'] = 0;
                        }
                        $Goods->sales_sum = $store_info['sale_num'];
                        $Goods->points =  $store_info['koudian'];
                        if($store_info['goods_examine']){
                            $Goods->goods_state = 0; // 待审核
                            $Goods->is_on_sale = 0; // 未上架 //20181130  tianxin100修复未审核商品上架问题

                        }else{
                            $Goods->goods_state = 1; // 出售中
                        }

                        if(empty($_POST['myitems'])){
                            $this->ajaxReturn(json_encode(array('status' => -1,'msg'=> '商品规格不能为空','data'  =>'')));
                        }

                        $goods_id = $Goods->add(); // 新增数据到数据库
                        $mydata['goods_id'] = $goods_id;
                        M('spec_item')->data($mydata)->where('id in('.$_POST['myitems'].')')->save();
                        $tiaozhuan=U('Goods/goodsList');
                    }
                    $Goods->afterSave($goods_id,STORE_ID);
//                    $GoodsLogic->saveGoodsAttr($goods_id,$type_id,STORE_ID); // 处理商品 属性
                    $GoodsLogic->saveGoodsAttr($goods_id,$_POST['goods_type'],STORE_ID); // 处理商品 属性
                    
                    cart_price($goods_id);
             
                           
                    //更新产品最低价
                    $minPrice = M('spec_goods_price')->where(['price'=>['gt',0.01],'store_count'=>['gt',0]])->where('goods_id=' . $goods_id)->min('price');

                    if($minPrice){
                        M('goods')->where('goods_id=' . $goods_id)->save(['shop_price' => $minPrice]);
                    }

                    
                    //处理广西的同步 by sofwu   start
                    // $sync_store_name = M('sync_account')->where(['store_id'=>STORE_ID,'tag'=>'guangxi'])->getField('store_name');
                    // if($sync_store_name){
                    //     if($type == 2){
                    //         $param['action'] = 'edit';
                    //     }else{
                    //         $param['action'] = 'add';
                    //     }
                    //     $param['store_name'] = $sync_store_name;
                    //     $param['from_plat'] = 'https://cdn.tlcwjsc.com';
                    //     $good = M('goods')->where(['goods_id'=>$goods_id])->find();
                    //     $good['old_goods_name'] = isset($old_goods_name) ? $old_goods_name['goods_name']: $good['goods_name'];
                    //     $good['images'] = M('goods_images')->field('image_url,sort_id')->where(['goods_id'=>$good['goods_id']])->select();
                    //     $good['goodstype_name'] = M('store_goods_class')->where(['cat_id'=>$good['store_cat_id1']])->getField('cat_name');
                    //     $spec = M('spec_item a')->field('a.*,b.name as spec_name,b.order,c.name as type_name,d.src')
                    //         ->join('ty_spec b on a.spec_id = b.id','LEFT')
                    //         ->join('ty_goods_type c on b.goods_type_id = c.id','LEFT')
                    //         ->join('ty_spec_image d on a.id = d.spec_image_id','LEFT')
                    //         ->where(['a.goods_id'=>$good['goods_id'],'a.store_id'=>STORE_ID,'c.name'=>['exp','IS NOT NULL']])->select();

                    //     $good['spec'] = $spec;

                    //     $specPrice = M('spec_goods_price')->where(['goods_id'=>$good['goods_id']])->select();
                    //     $good['spec_price'] = $specPrice;
                    //     if($good['points'] <=1){
                    //         $good['points'] = 1;
                    //     }
                    //     $param['goods_data'] = json_encode($good);
                    //     $url = C('SYNC_URL')['guangxi'].'/WXAPI/sync/saveGoods';
                    //     $callback = httpRequest($url,'POST',$param);
                    //     // var_dump($callback);
                    //     Log::record($callback,'DEBUG');
                    // }


                    //处理广西的同步 by sofwu   end

                    $return_arr = array(
                        'code' => 1,
                        'msg'   => '操作成功',
                        'data'  => I(''),
                    );
                    //重定向, 调整之前URL是设置参数获取方式
                    session("is_back" , 1);

                    M()->commit();
                }catch (Exception $e){
                    Log::record($e->getMessage(),'ERR');
                    $return_arr = array(
                        'code' => 0,
                        'msg'   => '操作失败',
                        'data'  => I(''),
                    );

                    M()->rollback();
                }
                $this->ajaxReturn($return_arr,'JSON');
               // form表单提交
               // C('TOKEN_ON',true);


                }  
            }



    }


    /**
     * 获取商品规格类型
     * */
    public function getType(){
        $goodsType = M("GoodsType")->where(array('store_id'=>STORE_ID))->select(); //获取当前店铺的商品类型
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$goodsType);
        $this->ajaxReturn($return_arr);
    }
    /**
     * 新增規格名稱
     * */
    public function addSpecItem(){

        $spec_id = I('spec_id',0); // 规格id
        $goods_id=I('goods_id',0);
        $spec_item = I('spec_item','','trim');// 规格项

        //php检测非法字符的一种方法
        $illegal_character="#['!`~\/\\\^=\$\:;<>\]\[{}]#";

        if(preg_match($illegal_character,$spec_item)){
            $return_arr = array(
                'code' => 0,
                'msg'   => '规格存在非法符号',
                'data'  =>'',
            );
            exit(json_encode($return_arr));
        }

        $c = M('spec_item')->where("store_id = ".STORE_ID." and item = '$spec_item' and goods_id = '$goods_id' and spec_id = $spec_id")->count();
        if($c > 0)
        {
            $return_arr = array(
                'code' => 0,
                'msg'   => '规格已经存在',
                'data'  =>'',
            );
            exit(json_encode($return_arr));
        }
        $data = array(
            'spec_id'=>$spec_id,
            'item'=>$spec_item,
            'store_id'=>STORE_ID,
            'goods_id'=>$goods_id,
            'sort'=>M('spec_item')->where("store_id = ".STORE_ID." and goods_id = '$goods_id' and spec_id = $spec_id")->max('sort')+1
        );
        $spec_item = D('specItem');
        $spec_item->create(NULL,0);
        $row = $spec_item->add($data);

        $return_arr = array(
            'code' => 1,
            'msg'   => '添加成功!',
            'data'  =>M('spec_item')->where(['id'=>$row])->find(),
        );
        exit(json_encode($return_arr));
    }
    /**
     * 商家发布商品时删除的规格
     */
    public function delSpecItem(){
        $spec_id = I('spec_id',0); // 规格id
        //$spec_item = I('spec_item','','trim');// 规格项
        $id = I('spec_item_id',0); //规格项 id

        if(empty($id))
        {

            $return_arr = array(
            'code' => 0,
            'msg'   => '没有id',
            'data'  =>'',
        );
            exit(json_encode($return_arr));
        }
        $c = M("order_goods")->where("store_id = ".STORE_ID." and  (spec_key like '%_{$id}' or spec_key like '%_{$id}_%' or spec_key like '{$id}_%') or spec_key = '{$id}' ")->count(); // 其他订单用到这个规格不得删除
        if($c)
        {
            $return_arr = array('code' => 0,'msg'=> '此规格已有订单,不得删除！点击可取消使用。');
            exit(json_encode($return_arr));
        }

        $specItem =  M('spec_item')->where("id = $id and spec_id= $spec_id")->find();

        M('spec_item')->where("id = $id and spec_id= $spec_id")->delete(); // 删除规格项
        M("spec_goods_price")->where("(`key` like '%_{$id}' or `key` like '%_{$id}_%' or `key` like '{$id}_%') or `key` = '{$id}' ")->delete(); // 删除规格价格
        M('spec_image')->where("spec_image_id = $id and store_id = ".STORE_ID)->delete(); // 删除规格图片选项



        //删除同步五鲸  by sofwu start
//        $sync_store_name = M('sync_account')->where(['store_id'=>STORE_ID,'tag'=>'wujing'])->getField('store_name');
//        if($sync_store_name){
//            $goods = M('goods')->where(['goods_id'=>$specItem['goods_id']])->find();
//
//            $param['store_name'] = $sync_store_name;
//            $param['spec_name'] = $specItem['item'];
//            $param['goods_name'] = $goods['goods_name'];
//
//            $url = C('SYNC_URL')['wujing'].'/WXAPI/sync/delGoodsSpec';
//            $callback = httpRequest($url,'POST',$param);
////            Log::record($callback,'DEBUG');
//        }
        //删除同步五鲸  by sofwu end

        $return_arr = array('code' => 1,'msg'=> '删除成功!','data'=>[]);
        exit(json_encode($return_arr));
    }
    /**
     * 增加/编辑规格类型
     * */
    public function saveGetType(){
        $data = I('');
        $id = $data['id'];
        $data['store_id'] = STORE_ID;
        $model = M('goods_type');
        // 编辑操作
        if($id){
            unset($_POST['id']);
            $res=$model->where(array('id'=>$id))->save($data);
            if ($res){
                $return_arr = array(
                    'code' => 1,
                    'msg'   => '修改成功',
                );
                exit(json_encode($return_arr));
            }else{
                $return_arr = array(
                    'code' => 0,
                    'msg'   => '修改失败',
                );
                exit(json_encode($return_arr));
            }
        }
        else // 添加操作
        {
            unset($_POST['id']);
            $res = $model->add($data);
            if ($res){
                $return_arr = array(
                    'code' => 1,
                    'msg'   => '添加成功',
                );
                exit(json_encode($return_arr));
            }else{
                $return_arr = array(
                    'code' => 0,
                    'msg'   => '添加失败',
                );
                exit(json_encode($return_arr));

            }

        }
    }
    /**
     * 删除规格类型
     * */
    public function DelGetType(){
        $id = I('id');
        M('goods_type')->where(array('id'=>$id))->delete();
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>[]);
        $this->ajaxReturn($return_arr);
    }
    /**
     *动态获取商品规格选择框
     * */

    public function ajaxGetSpecSelect_tianxin(){

        $goods_id = I('goods_id',0);
        $cat_id3 = I('cat_id3',0);
        empty($cat_id3) && exit('');
        $goods_id = $goods_id ? $goods_id : 0;
        $store_id=STORE_ID;
        $specList = D('Spec')->where("goods_type_id=$cat_id3  AND store_id='$store_id'")->order('`order` asc')->select(); // 找出这个类型的所有规格

        //$items_id = M('spec_goods_price')->where("goods_id = $goods_id")->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");

        $items_id =M('spec_goods_price')->field("key")->where("goods_id =".$goods_id)->select();
        foreach($items_id as $v){
            $myitem_id.=$v['key'].'_';
        }
        $myitem_id=rtrim($myitem_id, "_");
        $items_ids = explode('_', $myitem_id);

        foreach($specList as $k => $v){
            $specitem=D('SpecItem')->where("store_id = ".STORE_ID." and spec_id = ".$v['id'])->getField('id,item');
            if($goods_id){
                $specList[$k]['spec_item'] =D('SpecItem')->where("store_id = ".STORE_ID." and spec_id = ".$v['id']." and goods_id=".$goods_id)->order("sort asc")->getField('id,item'); // 修改获取规格项
                foreach ($specList[$k]['spec_item'] as $key=>$value){
                    if(in_array($key,$items_ids)){
                        $specList[$k]['spec_item_status'][$key] = 1;
                    }else{
                        $specList[$k]['spec_item_status'][$key] = 2;
                    }
                }
//                $specList[$k]['spec_item_status']
            }else{
                $specList[$k]['spec_item'] =D('SpecItem')->where("store_id = ".STORE_ID." and spec_id = ".$v['id']." and goods_id=0")->order("sort asc")->getField('id,item'); // 修改获取规格项
            }
        }

        // 获取商品规格图片
//        if($goods_id)
//        {
//            $specImageList = M('Spec_image')->where("goods_id = $goods_id")->getField('spec_image_id,src');
//            foreach ($specImageList as $k=>$item){
//                if($item){
//                    $specImageList[$k] = $item;
////                    $specImageList[$k] = !file_get_contents(SITE_URL.'/'.$item) ? C('MYOSS')['url'].$item : $item;
//
//                }
//            }
//
//        }
        $return_arr = array('code' => 1,'msg' => '操作成功','data'  =>$specList);
        $this->ajaxReturn($return_arr);
    }
    /**
     * 规格内容新增/编辑
     * */
    public function addEditSpec(){

        $data = I('');
        $model = M('spec');
        $store_id=STORE_ID;

        $type = $data['id'] > 0 ? 1: 0; // 标识自动验证时的 场景 1 表示插入 2 表示更新
        $data['store_id']=$store_id;
        $data['search_index']=1;
        if ($type)
        {
            $model->where(['id'=>$data['id']])->save($data); // 写入数据到数据库
        }
        else
        {
            $insert_id = $model->add(); // 写入数据到数据库
            //商品类型和规格对应表
            if($insert_id && !empty($_POST['goods_type_id']))
            {
                $dataList = array('type_id'=>$_POST['goods_type_id'],'spec_id'=>$insert_id);
                M('spec_type')->add($data);
            }
        }


        $return_arr = array(
            'code' => 1,
            'msg'   => '操作成功',
            'data'  => [],
        );
        $this->ajaxReturn($return_arr);

    }

    /**
     * 删除商品规格
     */
    public function delGoodsSpec()
    {
        $data = I('');
        // 判断 商品规格项
        $count = M("SpecItem")->where(['spec_id'=>$data['id']])->count();
       
        if($count > 0){
            $return_arr = array(
                'code' => 1,
                'msg'   => '此规格有规格值不得删除',
                'data'  => [],
            );
            $this->ajaxReturn($return_arr);
        }

//        $count > 0 && $this->error('此规格有规格值不得删除!',U('Seller/GoodsTianxin/specList',array('goods_type_id'=>$data['goods_type_id'])));
        // 删除分类

        M('Spec')->where(['id'=>$data['id']])->delete();
        M('spec_type')->where(['type_id'=>$data['goods_type_id'],'spec_id'=>$data['id']])->delete();
        $return_arr = array(
            'code' => 1,
            'msg'   => '操作成功',
            'data'  => [],
        );
        $this->ajaxReturn($return_arr);
//        $this->success("操作成功!!!",U('Seller/GoodsTianxin/specList',array('goods_type_id'=>$data['goods_type_id'])));
    }


    /**
     * 商品详情
     * */
    public function goodsDetail(){
        $goods_id = I('goods_id');
        $GoodsLogic = new GoodsLogic();
        if(empty($goods_id)){
            $return_arr = array(
                'code' => 0,
                'msg'   => '数据错误',
                'data'  => [],
            );
            $this->ajaxReturn($return_arr);
        }
        $goodsInfo =M('Goods')->where('goods_id='.$goods_id)->find();
        $goodsInfo['goods_content'] = htmlspecialchars_decode($goodsInfo['goods_content']);
        $goodsInfo['original_img2'] = $goodsInfo['original_img'];
        $goodsInfo['original_img'] = !file_get_contents(SITE_URL.'/'.$goodsInfo['original_img']) ? C('MYOSS')['url'].$goodsInfo['original_img'] : C('MYOSS')['url2'].$goodsInfo['original_img'];



        $store = M('store')->where(array('store_id'=>STORE_ID))->find();

//        $cat_list = M('goods_category')->where("parent_id = 0")->select();//自营店已绑定所有分类

//        $store_goods_class_list = M('store_goods_class')->where("parent_id = 0 and store_id = ".STORE_ID)->select(); //店铺内部分类
//        $brandList = $GoodsLogic->getSortBrands($goodsInfo['cat_id1']);
        $goodsType = M("GoodsType")->where(array('store_id'=>STORE_ID))->select(); //获取当前店铺的商品类型

        $suppliersList = M("suppliers")->select();
        $plugin_shipping = M('plugin')->where(array('type'=>array('eq','shipping')))->select();//插件物流
//        $shipping_area = D('shipping_area')->getShippingArea(STORE_ID);//配送区域
        $goods_shipping_area_ids = explode(',',$goodsInfo['shipping_area_ids']);

//
//        $this->assign('goods_shipping_area_ids',$goods_shipping_area_ids);
//        $this->assign('shipping_area',$shipping_area);
//        $this->assign('plugin_shipping',$plugin_shipping);
//        $this->assign('cat_list',$cat_list);
//        $this->assign('store_goods_class_list',$store_goods_class_list);
//        $this->assign('brandList',$brandList);
//        $this->assign('goodsType',$goodsType);
//        $this->assign('suppliersList',$suppliersList);
        $goodsInfo['guanlian']=\str_replace(',,',',',$goodsInfo['guanlian']);
        if(!empty($goodsInfo['guanlian'])){
            $goodsInfo['guanlian_list']=M("Goods")
                ->field('goods_id,goods_name,store_count,shop_price')
                ->where('goods_id in('.$goodsInfo['guanlian'].')')
                ->order('goods_id desc')
                ->select();
        }
//        $this->assign('goodsInfo',$goodsInfo);  // 商品详情
//        // 20181020 增加相片排序 亮 START
        $goodsImages = M("GoodsImages")->where('goods_id ='.$goods_id)->order("sort_id asc")->select();
        foreach ($goodsImages as $k=>$v){
            $goodsImages[$k]['image_url2'] = $v['image_url'];
            // if(!file_get_contents(SITE_URL.'/'.$v['image_url'])){
            //     $goodsImages[$k]['image_url'] = C('MYOSS')['url2'].$v['image_url'];
            // }else{
            //     $goodsImages[$k]['image_url'] = C('MYOSS')['url2'].$v['image_url'];
            // }
            $goodsImages[$k]['image_url'] = C('MYOSS')['url2'].$v['image_url'];

        }
//        // 20181020 增加相片排序 亮 END
//        $this->assign('goodsImages',$goodsImages);  // 商品相册
//
        $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => [
                'goodsInfo'=>$goodsInfo,
                'GoodsImages'=>$goodsImages,
                'goods_shipping_area_ids'=>$goods_shipping_area_ids,
//                'plugin_shipping'=>$plugin_shipping,
//                'cat_list'=>$cat_list,
//                'store_goods_class_list'=>$store_goods_class_list,
//                'brandList'=>$brandList,
//                'goodsType'=>$goodsType,
//                'suppliersList'=>$suppliersList
            ]
        );
        $this->ajaxReturn($return_arr);
    }

    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput(){
        $GoodsLogic = new GoodsLogic();
        $goods_id = I('goods_id','');
        $spec_arr = I('spec_arr');
        $str = $GoodsLogic->getSpecInput($goods_id ,$spec_arr,STORE_ID,1);

        $return_arr = array(
            'code' => 1,
            'msg'   => '操作成功',
            'data'  => $str,
        );
        $this->ajaxReturn($return_arr);
    }


    /**
     * 订单批量打印 by sofwu
     * @param int $id 订单id
     */
    public function order_print_pl(){

       function mypng($order_id,$jian,$type=1){
            $mydata = \json_encode([
                (int)$order_id,$jian
            ]);
            $picname=\md5($mydata);

            if($type==1){
                $filename = '/Public/goodsqrcode/erwei/'.$picname.'.png';
                Vendor('phpqrcode.phpqrcode');
                $object = new \QRcode();
                $level = 'Q'; //容错级别 分为L、M、Q、H
                $size = 6; //点的大小 1~10,手机端用4即可
                if (!file_exists($filename)) {
                    $object->png($mydata,'.'.$filename,$level,$size);
                }
            }else{
                $filename = './Public/goodsqrcode/erwei/'.$picname.'.png';
                $font = new BCGFontFile('./ThinkPHP/Library/Vendor/yiwei/font/Arial.ttf', 18);
                $color_black = new BCGColor(0, 0, 0);
                $color_white = new BCGColor(255, 255, 255);
                $drawException = null;
                try {
                    $code = new BCGcode128();
                    $code->setScale(2); // Resolution
                    $code->setThickness(30); // Thickness
                    $code->setForegroundColor($color_black); // Color of bars
                    $code->setBackgroundColor($color_white); // Color of spaces
                    $code->setFont(0); // Font (or 0)
                    $code->setStart(null);
                    $code->setTilde(true);
                    $code->parse($mydata); // Text
                } catch (Exception $exception) {
                    $drawException = $exception;
                }
                if (!file_exists($filename)) {
                    $drawing = new BCGDrawing('', $color_white);
                    $drawing->setBarcode($code);
                    $drawing->setFilename($filename);
                    $drawing->draw();
                    $drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
                }
            }
            $picurl=SITE_URL.$filename;
            return $picurl;
        }



        $order_ids = I('order_ids');
        if(empty($order_ids)){
            $return_arr = array(
                'code' => 0,
                'msg'   => '非法操作',
                'data'  => [],
            );
            $this->ajaxReturn($return_arr);
        }


        // 搜索条件
        $orderLogic = new OrderLogic();

        $orders = M('order a')
            ->field('a.*,b.mobile,b.company,b.biaoshi,b.biaoshi_xian,b.fast_flag,is_hide_phone')
            ->join('ty_users b on a.user_id=b.user_id','LEFT')
            ->where("a.order_id in($order_ids) and a.store_id=".STORE_ID)->order('order_id desc')->select();

        $store=M('store')->where("store_id=".STORE_ID)->find();

        $print_data=$print_datab=[];

        foreach($orders as $key=>$vs){
            //批量打印单据
            if($vs['order_id']){
                $orders[$key]['full_address'] = getRegionName($vs['province']).' '.getRegionName($vs['city']).' '.getRegionName($vs['district']).' '. $vs['address'];

                $orders[$key]['g_list'] = $orderLogic->getOrderGoods($vs['order_id']);
                $orders[$key]['fast_flag'] = $vs['fast_flag'] ? '快线' :'';
                // $orders[$key]['mobile'] = $vs['is_hide_phone'] ? '***********' : $vs['mobile'];
                $orders[$key]['mobile'] = $vs['mobile'];
                update_user_level($vs['user_id']);

                $print_data[]=[
                    'jian_count'=>$vs['jian_count'],
                    'biaoshi'=>$vs['biaoshi']?$vs['biaoshi']:'',
                    'biaoshi_xian'=>$vs['biaoshi_xian']?$vs['biaoshi_xian']:'',
                    // 'b1'=>$vs['b1'],
                    // 'b2'=>$vs['b2'],
                    // 'b3'=>$vs['b3'],
                    'fast_flag'=>$vs['fast_flag'] ? '快' :'',
                    'order_sn'=>$vs['order_sn'],
                    'company'=>$vs['company'],
                    // 'mobile'=> $vs['is_hide_phone'] ? '***********' : $vs['mobile'],
                    'mobile'=> $vs['mobile'],
//                    'full_address'=>$orders[$key]['full_address'],
                    // 'full_address'=> $vs['is_hide_phone'] ? '***********' : $orders[$key]['full_address'],
                    'full_address'=> $orders[$key]['full_address'],
                    'g_list'=>$orders[$key]['g_list'],
                    'total_amount'=>$vs['total_amount'],
                    'order_amount'=>$vs['order_amount'],
                    'coupon_price'=>$vs['coupon_price'],
                    'store_name'=>$store['store_name'],
                    'store_phone'=>$store['store_phone'],
                    'user_note'=>$vs['user_note'],
                    'add_time'=>date("Y-m-d H:i",$vs['add_time'])
                ];
            }

            // 批量标签
            $pic_data=[];
            if($vs['jian_count']>=1){
                for($i=1;$i<=(int)$vs['jian_count'];$i++){
                    $erwei=mypng($vs['order_id'],$i,1);
                    $pic_data[$i]=\pic64($erwei);
                }
            }
            $orders[$key]['pic_data']=$pic_data;
            $print_datab[]=[
                'erweima'=>$pic_data,
                // 'b1'=>$vs['b1']?$vs['b1']:'',
                // 'b2'=>$vs['b2']?$vs['b2']:'',
                // 'b3'=>$vs['b3']?$vs['b3']:'',
                'fast_flag'=>$vs['fast_flag']?'快':'',
                'biaoshi_xian'=>$vs['biaoshi_xian'],
                'jian_count'=>(int)$vs['jian_count'],
                'company'=>$vs['company'],
                'order_sn'=>$vs['order_sn'],
                'store_name'=>$store['store_name'],
                'shijian'=>date("Y/m/d")
            ];
        }

        $return_arr = array(
            'code' => 1,
            'msg'   => '操作成功',
            'data'  => ['orders'=>$orders,'print_data'=>$print_data,'print_datab'=>$print_datab,'store'=>$store,'platform'=>'ddt'],
        );
        $this->ajaxReturn($return_arr);
    }
    
     /**
     * 拣货清单
     * */
    public function pickingList(){$showPage = $page*$limit;
        $condition = array('a.store_id'=>STORE_ID); // 商家id
        $condition['order_status'] = 0;
        $count = M('order a')
            ->field('b.goods_id')
            ->join('ty_order_goods b on a.order_id=b.order_id','LEFT')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->group('b.goods_id')
            ->where($condition)->select();
        $goodsList = [];
        if(!empty($count)){
            foreach ($count as $k=>$v){
                $goodsData = M('order_goods a')
                    ->field('o.order_sn,a.goods_id,goods_name,a.spec_key_name,a.goods_num,a.spec_key,a.member_goods_price')
                    ->join('ty_order o on o.order_id = a.order_id','LEFT')
                    ->where(['a.goods_id'=>$v['goods_id'],'a.store_id'=>STORE_ID,'o.order_status'=>0])
                    ->group('a.spec_key')
                    ->select();
                if(!empty($goodsData)){
                    $goodsList[$k] = $goodsData;
                    foreach ($goodsList[$k] as $key=>$value){
                        $SumGoods = M('order_goods a')
                            ->join('ty_order o on o.order_id = a.order_id','LEFT')
                            ->where(['a.goods_id'=>$v['goods_id'],'a.store_id'=>STORE_ID,'o.order_status'=>0,'spec_key'=>$value['spec_key']])
                            ->sum('goods_num');
                            $goods = M('goods')->where(['goods_id'=>$value['goods_id']])->find();
                            $goodsList[$k][$key]['goods_num'] = $SumGoods;
                            $goodsList[$k][$key]['original_img'] = C('MYOSS')['url2'].$goods['original_img'];
                        
                    }
                } 
            }
        }
        $goodsList = array_values($goodsList);
         $return_arr = array(
            'code' => 1,
            'msg'   => '操作成功',
            'data'  => $goodsList,
        );
        $this->ajaxReturn($return_arr);
    }




    /**
     * 开启扫码入库功能
     * @return void
     */
    public function qrOpenSan()
    {
        $curr_time = I('curr_time');
        $user_id = SELLER_USER_ID;
        $expired = M('pda_expired')->where(['user_id'=>$user_id])->find();
        if($expired){
            M('pda_expired')->where(['user_id'=>$user_id])->save(['expired'=>15,'add_time'=>$curr_time]);
        }else{
            M('pda_expired')->add(['expired'=>15,'add_time'=>$curr_time,'user_id'=>$user_id]);
        }
        exit(json_encode(array("code"=>'1','msg'=>'成功开启扫码入库模式，15分钟后失效','data'=>[])));
    }

    /**
     * 扫码取货
     * @return void
     */
    public function saveReturn()
    {
        $id = I('id');
        $supplier_id = SELLER_USER_ID;
        $return = M('return_goods')->where(['id'=>['in',$id]])->find();
        $store = M('store')->where(['user_id'=>$supplier_id])->find();

        if($store['store_id'] != 22687){
            if($store['store_id'] != $return['store_id']){
                exit(json_encode(array("code"=>0,'msg'=>'你不是订单的商家','data'=>[])));
            }
        }

        M('return_goods')->where(['id'=>['in',$id]])->save(['getorder'=>1,'getorder_time'=>date('Y-m-d H:i:s',time())]);
        exit(json_encode(array("code"=>'1','msg'=>'取货成功','data'=>[])));


    }


    /**
     * 供应商手机入库
     * @return void
     */
    public function ruku(){
        $mobile_san = I('mobile_san');
        if($mobile_san){  //by sofwu 手机扫码入库
            $supplier_id = SELLER_USER_ID;
            $pda_expired = M('pda_expired')->where(['user_id'=>$supplier_id])->find();
            $store = M('store')->where(['user_id'=>$supplier_id])->find();
            if(!$pda_expired && !$store['open_san']){
                exit(json_encode(array("code"=>0,'msg'=>'你还没有开启扫码入库模式','data'=>['msg'=>'你还没有开启扫码入库模式'])));
            }
            $expired = $pda_expired['expired'];
            $expired_time = $pda_expired['add_time'];
            $san_time = strtotime('+'.$expired.' minutes',strtotime($expired_time));
            $now = time();
            if($san_time < $now && !$store['open_san']){
                exit(json_encode(array("code"=>0,'msg'=>'启扫码入库模式已经超时','data'=>['msg'=>'启扫码入库模式已经超时'])));
            }
        }
        $order_id=I("order_id");
        $ruku_num=I("ruku_num");
        $pda_name_ruku=I("pda_name_ruku");
        $pda_pd=M('pda')->where('pda_name="'.$pda_name_ruku.'"')->getField('fenbu_id'); //0广佛，1其他分部
        $pd=M('order')->where('order_id='.$order_id.' and order_status in (3,5)')->find();
        $order=M('order')->where('order_id='.$order_id)->find();
        if($pd){
            exit(json_encode(array("code"=>0,'msg'=>'此单已取消！','data'=>['msg'=>'此单已取消！'])));
        }else{
            $pd_quyu=M('order')->where('order_id='.$order_id)->getField('ufenbu_id');
            if($pda_pd!=0 && $pda_pd!=$pd_quyu){
                exit(json_encode(array("code"=>0,'msg'=>'此单不是该区域！','data'=>['msg'=>'此单不是该区域'])));
            }
            if($store['store_id'] != 22687){
                if($store['store_id'] != $order['store_id']){
                    exit(json_encode(array("code"=>0,'msg'=>'你不是订单的商家','data'=>['msg'=>'你不是订单的商家'])));
                }
            }

        }
        $basic = tpCache('basic');
        $fast_ruku_time = $basic['fast_ruku_time'];
        $slow_ruku_time = $basic['slow_ruku_time'];
        $now = time();
       
        if($fast_ruku_time && $slow_ruku_time) {
            $fast_time = explode('-', $fast_ruku_time);
            $slow_time = explode('-', $slow_ruku_time);
            $fast_start_time = strtotime($fast_time[0]);
            $fast_end_time = strtotime($fast_time[1]);
            $slow_start_time = strtotime($slow_time[0]);
            $slow_end_time = strtotime($slow_time[1]);
            $fast_flag = M('order a')
                ->join('ty_users b ON a.user_id = b.user_id', 'LEFT')
                ->where(['a.order_id' => $order_id])->getField('b.fast_flag');
            if ($fast_flag) {
                if (($now > $fast_start_time) && ($now < $fast_end_time)) {
        //             echo I('callback')."(".json_encode([
    				// 	'code'=>'50',
    				// 	'infos'=>'快线订单禁止入库！'
    				// ]).")";
    				// exit;
    				exit(json_encode(array("code"=>0,'msg'=>'快线订单禁止入库!','data'=>['msg'=>'快线订单禁止入库!'])));
                    // exit(json_encode(array("status"=>0,'msg'=>'快线订单禁止入库!')));
                }
            } else {
                if (($now > $slow_start_time) || ($now < $slow_end_time)) {
        //             echo I('callback')."(".json_encode([
    				// 	'code'=>'50',
    				// 	'infos'=>'订单禁止入库！'
    				// ]).")";
    				// exit;
    				
    				exit(json_encode(array("code"=>0,'msg'=>'订单禁止入库！','data'=>['msg'=>'订单禁止入库!'])));
                    // exit(json_encode(array("status"=>0,'msg'=>'订单禁止入库!')));
                }
            }
        }
        //判断总部和分部字段
        $z=  '';

        $orders=M('order_jian a')
            ->field('a.*,b.order_sn,b.consignee,b.jian_count')
            ->join('ty_order b on a.order_id=b.order_id')
            ->where('a.order_id='.$order_id.' and a.'.$z.'status_r=0 and a.'.$z.'ruku_num='.$ruku_num)->find();
        $ruku_time = strtotime(date("Y-m-d H:i:s"));
       
        if($orders){
             M()->startTrans();
            try {
            M('order_jian')
                ->where('order_id='.$order_id.' and '.$z.'status_r=0 and '.$z.'ruku_num='.$ruku_num)
                ->save([
                    $z.'pda_name_ruku'=>$pda_name_ruku,
                    $z.'ruku_time'=>$ruku_time,
                    $z.'status_r'=>'1',
                    'status_c'=> !empty($pda_pd) ? '1' : '0'
                ]);
           
            M('order')->where('order_id='.$order_id)->setInc('ruku_count');
            $ruku_order = M('order')->where('order_id='.$order_id)->find();
          
            if($ruku_order['jian_count'] == $ruku_order['ruku_count']){  //判断是否入库齐全才变已发货订单，司机待配送单那里才会有订单，不齐全的都会在异常订单
                M('order')->where('order_id='.$order_id)
                    ->save([
                        'order_status'=>1,
                        'shipping_status'=>1,
                        'ruku_last_time'=>$ruku_time
                    ]);
            }
            M()->commit();
             }catch (Exception $e){
                Log::record($e->getMessage(),'ERR');
                M()->rollback();
                exit(json_encode(array("status"=>0,'msg'=>'操作失败请重新扫码')));
            }
            exit(json_encode(array("code"=>1,'msg'=>'入库成功','data'=>['code'=>1,'msg'=>'入库成功'])));
        }else{
            exit(json_encode(array("code"=>0,'msg'=>'此单已经入库！','data'=>['code'=>0,'msg'=>'此单已经入库！'])));
        }

    }
      /**
     * 竞价关键词列表
     */
    public function cps_keys_list()
    {
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
        
        $model =  M('promotion_cps_keyword');
        $keyword = I('keywords');
        if($keyword) $map['keyword'] = array('like',"%$keyword%");
        $store = M('store')->where(['store_id'=>STORE_ID])->find();

        $count = $model->where($map)->count();
        $Page = new \Think\Page($count,100);
        $keys = $model->where(['store_class_id'=>$store['sc_id'],'status'=>1])->where($map)->order('sort')->limit($showPage,$limit)->select();
        $self_sort = 0;
        foreach ($keys as $k=>$item){
            $hot = M('user_record')->where(['keyword'=>$item['keyword']])->count();
            $key_goods = M('promotion_cps_goods')
                ->where(['keyword_id'=>$item['id'],'store_id'=>$store['store_id'],'status'=>1])
                ->where('end_time >= "'.date('Y-m-d H:i:s',time()).'"')
                ->find();
            $goods = [];
            if($key_goods && $key_goods['goods_id']){
                $goods = M('goods')->where(['goods_id'=>$key_goods['goods_id']])->find();
            }

            $key_goods_list = M('promotion_cps_goods')
                ->where(['keyword_id'=>$item['id'],'status'=>1])
                ->where('end_time >= "'.date('Y-m-d H:i:s',time()).'" and start_time <= "'.date('Y-m-d H:i:s',time()).'"')
                ->order('price desc')
                ->select();

            foreach ($key_goods_list as $key=>$good){
                if($good['store_id'] == STORE_ID){
                    $self_sort = $key+1;
                }
            }

            $keys[$k]['goods_name'] = isset($goods) ? $goods['goods_name'] : '';
            $keys[$k]['price'] = $key_goods['price'];
            $keys[$k]['self_sort'] = $self_sort;
            $keys[$k]['hot'] = $hot;
            $keys[$k]['time'] = $key_goods['start_time'].'~'.$key_goods['end_time'];
            $keys[$k]['cps_id'] = $key_goods['id'];

        }

        $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => ['list'=>$keys,'page'=>$page,'limit'=>$limit]
        );
        $this->ajaxReturn($return_arr);
    }


    /**
     * 添加竞价产品
     */
    public function cps_goods()
    {
        $cps_id = I('cps_id');
        $keys_id = I('keys_id');
        if($cps_id){
            $info = M('promotion_cps_goods')->where(['id'=>$cps_id])->find();
            $goods = M('goods')->where(['goods_id'=>$info['goods_id']])->find();
            $keys = M('promotion_cps_keyword')->where(['id'=>$keys_id])->find();
            $info['goods_name'] = $goods['goods_name'];
            $info['keyword'] = $keys['keyword'];
        }
        $key_goods = M('promotion_cps_goods')
            ->where(['keyword_id'=>$keys_id,'status'=>1])
            ->where('end_time >= "'.date('Y-m-d H:i:s',time()).'" and start_time <= "'.date('Y-m-d H:i:s',time()).'"')
            ->order('price desc')
            ->select();
        $self_sort = 0;
        foreach ($key_goods as $key=>$good){
            if($good['store_id'] == STORE_ID){
                $self_sort = $key+1;
            }
        }
        $info['keyword_id'] = $cps_id ? $info['keyword_id'] : $keys_id;
        $info['max_price'] = $key_goods && $key_goods[0]['price'] ? '最高出价：<span style="color: #f00">'.$key_goods[0]['price'].'</span> 元': '暂无出价';
        $info['self_sort'] = !$self_sort ? '暂无排名' : '你的排名是：'.'<span style="color: #f00">'.$self_sort.'</span>';
        $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => $info,
        );
        $this->ajaxReturn($return_arr);
    }

    /**
     * 竞技产品保存
     */
    public function cps_save(){
        $data = I('post.');
        $data['store_id'] = STORE_ID;
     
        if($data['price']){
            $price = M('promotion_cps_goods')
                ->where(['keyword_id'=>$data['keyword_id'],'price'=>$data['price'],'status'=>1])
                ->where('end_time >= "'.date('Y-m-d H:i:s',time()).'" and start_time <= "'.date('Y-m-d H:i:s',time()).'"')->find();
            if($price){
                $return_arr = array(
                    'code' => 0,
                    'msg'   => '提交失败,该时间段竞价金额已经存在',
                    'data'  => [],
                );
                 $this->ajaxReturn($return_arr);
            }
        }
        if($data['id'] > 0 || $data['act']=='del'){
            if($data['act']== 'del'){
                $r = M('promotion_cps_goods')->where("id=".$data['del_id'])->delete();
                respose(1);
            }else{
                $r = M('promotion_cps_goods')->where("id=".$data['id'])->save($data);
            }
        }else{
            $r = M('promotion_cps_goods')->add($data);
        }
        
        if($r){
            $return_arr = array(
                'code' => 1,
                'msg'   => '编辑成功',
                'data'  => [],
            );
        
        }else{
            $return_arr = array(
                'code' => 0,
                'msg'   => '提交失败',
                'data'  => [],
            );
        }
        $this->ajaxReturn($return_arr);
    }
    
      /**
     * 搜索产品
     */
    public function cps_search_goods()
    {
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
        $search_key = trim(I('search_key'));

        $where="(goods_name like'%$search_key%' or goods_id like'%$search_key%' )  and goods_state = 1 and is_on_sale = 1  and store_id=".STORE_ID;

        $list = M('goods')->where($where)->limit($showPage,$limit)->select();

        $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => ['page'=>$page+1,'list'=>$list,'limit'=>$limit],
        );
         $this->ajaxReturn($return_arr);
    }
    
     public function csp_detail(){
        $id = I('id');
        $detail = M('promotion_cps_goods')->where(['id'=>$id])->fidn();
         $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => $detail,
        );
         $this->ajaxReturn($return_arr);
    }
    
    
    public function sales_overview_detail(){

         $timegap = I('timegap');
        // $timegap = str_replace('~',' ',$timegap);
        if($timegap){
            $gap = explode(' ~ ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $lastweek = date('Y-m-d 00:00',strtotime("-15 day"));//30天前-1 month
            $begin = I('begin',$lastweek);
            $end =  I('end',date('Y-m-d 23:59:59'));
        }

        $this->begin = strtotime($begin);
      
        $this->end = strtotime($end);//+86399;
        $now = strtotime(date('Y-m-d'));
        $now_end = $now+86399;

        $currentMonthFirstDay = strtotime(date('Y-m'));
        $currentMonthLastDay = strtotime(date('Y-m'). ' +1 month -1 day')+86399;
        $today['month_amount'] = M('order')->where("add_time>$currentMonthFirstDay and add_time<$currentMonthLastDay AND order_status in(0,1,2) and store_id=".STORE_ID)->sum('total_amount');//今日销售总额
        $today['today_amount'] = M('order')->where("add_time>$now and add_time<$now_end AND order_status in(0,1,2) and store_id=".STORE_ID)->sum('total_amount');//今日销售总额
        if(empty($today['today_amount'])){
            $today['today_amount'] = 0;
        }
        if(empty($today['month_amount'])){
            $today['month_amount'] = 0;
        }
        $today['today_order'] = M('order')->where("add_time>$now and add_time<$now_end AND order_status in(0,1,2) and store_id=".STORE_ID)->count();//今日订单数
        $order_user = M('order')->where("add_time>$now and add_time<$now_end AND order_status in(0,1,2) and store_id=".STORE_ID)->group('user_id')->select();
		$today['today_users'] = \count($order_user); //时间下单人数
        $today['cancel_order'] = M('order')->where("add_time>$now and add_time<$now_end AND order_status=3 and store_id=".STORE_ID)->count();//今日取消订单
        $today['sign'] = sanwei($today['today_amount']/$today['today_order']);
        
        $res =M("order")
		    ->field("COUNT(order_id) as tnum,sum(total_amount) as amount,sum(kou_price) as kou_price, FROM_UNIXTIME(add_time,'%Y-%m-%d') as gap")
		    ->where("add_time>$this->begin and add_time<$this->end  AND order_status in(0,1,2,4) and store_id=".STORE_ID)
		    ->group("gap")
		    ->cache(true,3600)
		    ->select();


        foreach ($res as $val){
            $arr[$val['gap']] = $val['tnum'];
            $brr[$val['gap']] = $val['amount'];
            $drr[$val['gap']] = $val['kou_price'];
            $end_time=strtotime($val['gap'])+24*3600-1;
            $crr[$val['gap']] = count(M('order')->field('user_id')->where("add_time>".strtotime($val['gap'])." and add_time<".$end_time." and order_status in(0,1,2)")->group('user_id')->limit(16)->select());
            $tnum += $val['tnum'];
            $tamount += $val['amount'];
        }

        for($i=$this->end;$i>=$this->begin;$i=$i-24*3600){
            $tmp_num = empty($arr[date('Y-m-d',$i)]) ? 0 : $arr[date('Y-m-d',$i)];
            $tmp_amount = empty($brr[date('Y-m-d',$i)]) ? 0 : $brr[date('Y-m-d',$i)];
            $tmp_kou_price = empty($drr[date('Y-m-d',$i)]) ? 0 : $drr[date('Y-m-d',$i)];
            $tmp_users = empty($crr[date('Y-m-d',$i)]) ? 0 : $crr[date('Y-m-d',$i)];
            $tmp_sign = empty($tmp_num) ? 0 : sanwei($tmp_amount/$tmp_num);
            $order_arr[] = $tmp_num;
            $amount_arr[] = sanwei($tmp_amount);
            $users_num[]=$tmp_users;
            $sign_arr[] = $tmp_sign;
            $date = date('Y-m-d',$i);
			$list[] = array('day'=>$date,'order_num'=>$tmp_num,'amount'=>$tmp_amount,'kou_price'=>$tmp_kou_price,'users_num'=>$tmp_users,'sign'=>$tmp_sign,'end'=>date('Y-m-d',$i+24*60*60));
            $day[] = $date;
            
            $start_time = strtotime(date('Y-m-d',$i));
            $end_time = $i+59;
			$time[] = date('m-d',$i);
			
			$sumprice = M('order')->where("add_time>$start_time and add_time<=$end_time AND order_status in(0,1,2) and store_id = ".STORE_ID)->sum('order_amount');
			if($sumprice == null){
			    $sumprice = 0;
			}
			$price[] = geshi($sumprice);
			
			$countorder = M('order')->where("add_time>$start_time and add_time<$end_time AND order_status in(0,1,2) and store_id = ".STORE_ID)->count();
            $count[] = $countorder;
            
            $unit[] = geshi($sumprice/$countorder);
        }
		$last_names = array_column($list,'day');
		array_multisort($last_names,SORT_DESC,$list);
		$list2['time'] = $time;
		$list2['price'] = $price;
		$list2['count'] = $count;
		$list2['unit'] = $unit;
		$result = array('order'=>$order_arr,'amount'=>$amount_arr,'sign'=>$sign_arr,'time'=>$day);
		$return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => [
                'list'=>$list,
                'zongdan'=>M('order')->where("order_status in(0,1,2) and store_id=".STORE_ID)->cache(true,3600)->count(),
                'zongjine'=>M('order')->where("order_status in(0,1,2) and store_id=".STORE_ID)->cache(true,3600)->sum('total_amount'),
                'result'=>$result,
                'today'=>$today,
                'list2'=>$list2
                ],
        );
         $this->ajaxReturn($return_arr);
	
    }
    
     /*
     *获取文章分类
     */
     public function article_classifications(){
         $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => [
                0=>['id'=>25,'title'=>'重要通知-商家必读'],
                1=>['id'=>26,'title'=>'帮助中心']
                ]
        );
         $this->ajaxReturn($return_arr);
     }
          /*
     *获取文章分类列表
     */
     public function article_classification_list(){
         $page = I('page',1);
        $limit = I('limit',20);
      
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
         $showPage = $page*$limit;
        $map=[];
        $map['is_open']=1;
        $map['cat_id']=I('id');
        
        $keys = M('article')->where($map)->order('article_id desc')->limit($showPage,$limit)->select();
       
         $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => $keys,
        );
         $this->ajaxReturn($return_arr);
     }
     
     public function articleClassificationDetail(){
         
         $content = M('article')->where(['article_id'=>I('id')])->find();
         $content['content'] = htmlspecialchars_decode($content['content']);
         $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => $content,
        );
         $this->ajaxReturn($return_arr);
     }

    /**
     * 获取同步产品的数据接口
     * @return void
     */
     public function getSyncGoods()
     {
         $id = I('id');
         $goods = M('goods')->where(['is_on_sale'=>1,'goods_id'=>$id])->find(); //获取产品

         $goods['images'] = M('goods_images')->field('image_url,sort_id')->where(['goods_id'=>$goods['goods_id']])->select();
         $goods['goodstype_name'] = M('store_goods_class')->where(['cat_id'=>$goods['store_cat_id1']])->getField('cat_name');
         $spec = M('spec_item a')->field('a.*,b.name as spec_name,b.order,c.name as type_name,d.src')
             ->join('ty_spec b on a.spec_id = b.id','LEFT')
             ->join('ty_goods_type c on b.goods_type_id = c.id','LEFT')
             ->join('ty_spec_image d on a.id = d.spec_image_id','LEFT')
             ->where(['a.goods_id'=>$goods['goods_id']])->select();
         $goods['spec'] = $spec;

         $specPrice = M('spec_goods_price')->where(['goods_id'=>$goods['goods_id']])->select();
         $goods['spec_price'] = $specPrice;

         $json_str = json_encode(['code'=>1,'data'=>$goods,'msg'=>'获取成功'],true);
         exit($json_str);
     }


    /**
     * 同步产品搜索
     */
    public function sync_search_goods()
    {
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
        $search_key = trim(I('search_key'));

        if($search_key){
            $where="(goods_name like'%$search_key%' or goods_id like'%$search_key%' )  and goods_state = 1 and is_on_sale = 1 ";
        }else{
            $where=" goods_state = 1 and is_on_sale = 1 ";
        }


        $list = M('goods a')->field('a.*,b.store_name')->join('ty_store b ON a.store_id = b.store_id','left')->where($where)->order('sales_sum desc')->limit($showPage,$limit)->select();
        foreach ($list as &$item){
            $item['original_img'] = C('MYOSS')['url'].$item['original_img'];
        }
    
        $return_arr = array(
            'code' => 1,
            'msg'   => '获取成功',
            'data'  => ['page'=>$page+1,'list'=>$list,'limit'=>$limit,'from_plat'=>'https://static.ddtwj.com'],
        );
        $this->ajaxReturn($return_arr);
    }


    /**
     * 获取配送单列表
     * @return void
     */
    public function getDriverOrderList()
    {
        $p = I('page',0);
        $user_id = I('user_id');
        $type = I('type',1);
        $keys = I('keys');
        Log::record(json_encode(I('')),'DEBUG');
        $user = M('users')->where(['user_id'=>$user_id,'is_driver'=>1,'is_lock'=>0])->find(); //查询司机信息
        if($user && $user['biaoshi_xian']){
            $xian_user = M('users')->where(['biaoshi_xian'=>$user['biaoshi_xian']])->order('xsort asc')->getField('user_id',true);
            $condition = [];
            //$keys ? $condition['a.order_sn|b.company|b.mobile'] = ['like','%'.$keys.'%'] : false;

            if($keys){
                if(is_numeric($keys)){
                    $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.$keys.',order_sn) > 0');
                    foreach ($subQuery_orderIds as $item){
                        $ids[] = $item['order_id'];
                    }
                    if($ids){
                        $condition['a.order_id'] = ['in',join(',',$ids)];
                    }else{
                        $condition['a.order_id'] = 0;
                    }
                }else{
                    $condition['b.company|b.mobile'] = ['like','%'.$keys.'%'];
                }


            }

            if ($type == 1){ //待配送
                $condition['a.order_status'] = ['lt',3];
                $condition['a.driver_id'] = 0;
                $condition['a.user_id'] = ['in',join(',',$xian_user)];
            }elseif($type == 2){ //未支付
                $condition['a.pay_status'] = 0;
                $condition['a.driver_id'] = $user_id;


                $condition['a.user_id'] = ['in',join(',',$xian_user)];


            }elseif($type == 3){ //已支付
                $condition['a.pay_status'] = 1;
                $condition['a.driver_id'] = $user_id;

                $condition['a.user_id'] = ['in',join(',',$xian_user)];


            }elseif ($type ==4 ){ //异常
                $this->getReturnOrder($user,$keys,$p);
            }else{
                $condition['a.user_id'] = ['in',join(',',$xian_user)];
            }


            if($this->begin && $this->end){
                $condition['a.chuku_last_time'] = array('between',"$this->begin,$this->end");
            }

            $condition['a.shipping_status'] = 1;


            $condition['_string'] = 'a.chuku_count > 0  and a.jian_count > 0 and a.chuku_count = a.jian_count ';
            
            $count = M('order a')
                ->field('a.user_id')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->where($condition)->order('b.xsort asc')->group('a.user_id')
                ->select();


            $Page = new Page(count($count), 10);
            $Page->firstRow = $p * $Page->listRows;

            //获取订单列表
            $orderList = M('order a')
                ->field('a.user_id,b.company,b.mobile,a.driver_id,a.driver_time,a.pay_status,b.company_address,sum(a.order_amount + a.yijia_heji) as order_amount,sum(a.jian_count) as jian_count')
                ->join('ty_users b on a.user_id=b.user_id','LEFT')
                ->where($condition)
                ->limit("$Page->firstRow,$Page->listRows ")
                ->order('field(a.user_id,'.join(',',$xian_user).')')->group('a.user_id')->select(); //过滤获取主订单


            foreach($orderList as $key=>$v) { //整理子单
                $waitPayPrice = 0;

                $condition['a.user_id'] = $v['user_id'];
                unset($condition['b.company|b.mobile']);
                $order_list = M('order a')
                    ->field('c.store_name,a.driver_id,a.order_sn,a.pay_status,a.jian_count,(a.order_amount + a.yijia_heji) as order_amount,a.pay_status,a.order_id,a.unusual_remake,a.unusual_status,a.chuku_count')
                    ->join('ty_users b on a.user_id=b.user_id', 'LEFT')
                    ->join('ty_store c on a.store_id=c.store_id', 'LEFT')
                    ->where($condition)
                    ->order('a.order_id desc')
                    ->select(); //过滤获取主订单
                //查询产品
                foreach ($order_list as $k=>$v){
                    if($v['pay_status'] == 0){
                        $waitPayPrice+= $v['order_amount'];
                        $orderList[$key]["pay_status"] = 0;
                    }
                    $order_goods = M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.goods_name,((a.member_goods_price + a.yijia) * a.goods_num) as xiaoji,b.original_img,a.goods_num')->where(['order_id'=>$v['order_id']])->select();
                    foreach ($order_goods as $kk=>$vv){
                        $order_goods[$kk]['xiaoji'] = sanwei($vv['xiaoji']);
                        $order_goods[$kk]['goods_num'] = $vv['goods_num'];
                        $order_goods[$kk]['original_img'] = C('MYOSS')['url'].$vv['original_img'];
                    }
                    $order_list[$k]['goods'] = $order_goods;
                }
                $orderList[$key]['wait_pay_price'] = sanwei($waitPayPrice);
                $orderList[$key]["order_list"] = $order_list;
                if(!empty($v['driver_time'])){
                    $orderList[$key]['driver_time'] = date('Y-m-d H:i:s',$v['driver_time']);
                }else{
                    $orderList[$key]['driver_time'] = '未配送';
                }
            }
            exit(json_encode(array("code"=>1,'msg'=>'获取成功','data'=>$orderList,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));

        }else{
            $user = M('users')->where(['user_id'=>$user_id,'biaoshi'=>'售后员工'])->find(); //查询售后员工
            if(!$user){
                exit(json_encode(array("code"=>0,'msg'=>'你不是配送员或售后员工')));
            }
            exit(json_encode(array("code"=>1,'msg'=>'获取成功','data'=>[],'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));

        }
    }


    /**
     * 订单列表
     * */
    public function getDriverOrderMore(){
        $p = I('page', 0);
        $type = I('type',1);
        $user_id = I('user_id');
        $driver_id = I('driver_id');
        $condition = [];
        $keys = I('keys');
        if ($type == 1){ //待配送
            $condition['a.order_status'] = ['lt',3];
            $condition['a.driver_id'] = 0;
        }elseif($type == 2){ //未支付
            $condition['a.pay_status'] = 0;
            $condition['a.driver_id'] = $driver_id;
        }elseif($type == 3){ //已支付
            $condition['a.pay_status'] = 1;
            $condition['a.driver_id'] = $driver_id;
        }
        if($this->begin && $this->end){
            $condition['a.chuku_last_time'] = array('between',"$this->begin,$this->end");
        }


        if($keys){
            if(is_numeric($keys)){
                $subQuery_orderIds = M()->query('select order_id from ty_order WHERE LOCATE('.$keys.',order_sn) > 0');
                foreach ($subQuery_orderIds as $item){
                    $ids[] = $item['order_id'];
                }
                if($ids){
                    $condition['a.order_id'] = ['in',join(',',$ids)];
                }else{
                    $condition['a.order_id'] = 0;
                }
            }
        }

        $condition['a.user_id'] = $user_id;
        $condition['a.shipping_status'] = 1;
        $condition['_string'] = 'a.chuku_count > 0  and a.jian_count > 0 and a.chuku_count = a.jian_count ';

        $count = M('order a')
            ->field('c.store_name,a.driver_id,a.order_sn,a.pay_status,a.jian_count,(a.order_amount + a.yijia_heji) as order_amount,a.pay_status,a.order_id,a.unusual_remake,a.unusual_status,a.chuku_count')
            ->join('ty_users b on a.user_id=b.user_id', 'LEFT')
            ->join('ty_store c on a.store_id=c.store_id', 'LEFT')
            ->where($condition)
            ->order('a.order_id desc')
            ->select(); //过滤获取主订单

        $Page = new Page(count($count), 10);
        $Page->firstRow = $p * $Page->listRows;
        $order_list =M('order a')
            ->field('c.store_name,a.driver_id,a.order_sn,a.pay_status,a.jian_count,(a.order_amount + a.yijia_heji) as order_amount,a.pay_status,a.order_id,a.unusual_remake,a.unusual_status,a.chuku_count')
            ->join('ty_users b on a.user_id=b.user_id', 'LEFT')
            ->join('ty_store c on a.store_id=c.store_id', 'LEFT')
            ->where($condition)
            ->limit("$Page->firstRow,$Page->listRows ")
            ->order('a.order_id desc')
            ->select(); //过滤获取主订单
        foreach ($order_list as $k => $v) {
            $order_goods = M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.goods_name,((a.member_goods_price + a.yijia) * a.goods_num) as xiaoji,b.original_img,a.goods_num')->where(['order_id' => $v['order_id']])->select();
            foreach ($order_goods as $kk => $vv) {
                $order_goods[$kk]['xiaoji'] = sanwei($vv['xiaoji']);
                $order_goods[$kk]['goods_num'] = $vv['goods_num'];
                $order_goods[$kk]['original_img'] = C('MYOSS')['url'] . $vv['original_img'];
            }
            $order_list[$k]['goods'] = $order_goods;
        }
        exit(json_encode(array("code"=>1,'msg'=>'获取成功','data'=>$order_list,'extra'=>['begin'=>date('Y-m-d H:i',$this->begin),'end'=>date('Y-m-d H:i',$this->end)])));

    }

    /**
     * 获取退货单
     * @return void
     */
    public function getReturnOrder($user,$keys,$p)
    {
        $where='  ';
        if(!empty($keys))
            $where=' and ( c.company like "%'.$keys.'%" or b.store_name like "%'.$keys.'%" or a.order_sn like "%'.$keys.'%" ) ';

        $condition['_string'] = 'a.driver_id ='.$user['user_id'].$where;

        if($this->begin && $this->end){
            $condition['a.addtime'] = array('between',"$this->begin,$this->end");
        }
        $count = M('return_goods a')
            ->join('ty_store b ON a.store_id = b.store_id')
            ->join('ty_users c ON a.user_id = c.user_id')
            ->where($condition)->count();
        $Page = new Page($count, 20);

        $orders = M('return_goods a')->field('a.*,b.store_name,c.company,d.goods_name,e.key_name,d.original_img')
            ->join('ty_store b ON a.store_id = b.store_id')
            ->join('ty_users c ON a.user_id = c.user_id')
            ->join('ty_goods d ON a.goods_id = d.goods_id','LEFT')
            ->join('ty_spec_goods_price e ON a.spec_key = e.key','LEFT')
            ->where($condition)->order('a.id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($orders as $k=>$v){
            $orders[$k]['price'] = sanwei(($v['member_goods_price'] + $v['yijia']) * $v['goods_num']);
            $orders[$k]['member_goods_price'] = sanwei(($v['member_goods_price'] + $v['yijia']));
            $orders[$k]['original_img'] = C('MYOSS')['url'].$v['original_img'];
            $orders[$k]['imgs'] = C('MYOSS')['url'].$v['imgs'];
        }


        $return_arr = array('code' => 1, 'msg' => '成功', 'data' => $orders);
        exit(json_encode($return_arr));
    }


    /**
     * 司机操作配送单
     * @return void
     */
    public function setOrderDriver()
    {
        $order_id = I('order_id');
        $user_id = I('user_id');
        $user = M('users')->where(['user_id'=>$user_id])->find();
        if($user && $user['is_driver']){
            if($order_id){
                $master_order_sn = get_order_sn();
                M('pay_merge_log')->add(['master_order_sn'=>$master_order_sn,'order_sn'=>$order_id,'add_time'=>date('Y-m-d H:i:s',time())]); //记录合并订单
                M('order')->where('order_id in ('.$order_id.')')->save(['pay_master_order_sn'=>$master_order_sn,'driver_id'=>$user_id,'driver_time'=>time()]);
                $pay = new PayController();
                $payUrl = $pay->payApp($master_order_sn);


                $return_arr = array('code' => 1, 'msg' => '操作成功', 'data' => ['pay_url'=>$payUrl]);
                exit(json_encode($return_arr));
            }

        }else{
            exit(json_encode(array("code"=>0,'msg'=>'你不是配送员', 'data' => [])));
        }
    }

    public function payOrder()
    {
        $order_id = I('order_id');
    }


    /**
     * 司机登录
     * @return void
     */
    public function driverLogin(){
        $username = I('username');


        $user = M('users')->where("mobile='{$username}' and (is_driver=1 or biaoshi = '售后员工') ")->find();
        if(!$user){
            $result = array('code'=>0,'msg'=>'账号不存在!','data'=>[]);
        }elseif($user['is_lock'] == 1){
            $result = array('code'=>0,'msg'=>'账号异常已被锁定！！！','data'=>[]);
        }else{
            //查询用户信息之后, 查询用户的登记昵称
            $user['token'] = md5(time().mt_rand(1,999999999));
            M('users')->where("user_id = {$user['user_id']}")->save(array('token'=>$user['token'],'last_login'=>time()));
            $result = array('code'=>1,'msg'=>'登陆成功','data'=>$user);
        }


        if($result['code'] != 1)
            exit(json_encode($result));


        exit(json_encode($result));

    }


    /**
     * 司机操作退货获取订单产品
     * @return void
     */
    public function getOrderGoods()
    {
        $order_id=I('order_id',0);
        $list=M('order_goods a')->join('ty_goods b ON a.goods_id = b.goods_id')->field('a.*,b.original_img')->where('order_id='.$order_id)->select();
        foreach ($list as $k=>$v){
            $list[$k]['goods_num'] = round($v['goods_num']);
            $list[$k]['original_img'] = C('MYOSS')['url'].$v['original_img'];
            $list[$k]['member_goods_price'] = sanwei($v['member_goods_price']+$v['yijia']);
            $return_num = M('return_goods')->where(['order_id'=>$order_id,'goods_id'=>$v['goods_id'],'spec_key'=>$v['spec_key']])->sum('goods_num');
            $list[$k]['return_max'] = $list[$k]['goods_num']-$return_num;
        }
        $return_arr = array('code' => 1, 'msg' => '成功', 'data' => $list);
        exit(json_encode($return_arr));
    }

    /**
     * 司机操作退货
     * @return void
     */
    public function saveReturnOrder()
    {
        try {
            M()->startTrans();
            $result = file_get_contents("php://input");
            $result = json_decode($result,true);
            $goodGoods=json_decode($result['goodGoods'],true);

            $return_remark=$result['return_remark'];
            $imageUrl=$result['imageUrl'];
            if(!$return_remark){
                $return_arr = array('code' => 0, 'msg' => '请选择理由', 'data' => []);
                exit(json_encode($return_arr));
            }
            if($goodGoods){
                $order_sn = get_order_sn();
                foreach($goodGoods as $key=>$v){
                    $order_goods = M('order_goods')->where(['rec_id'=>$v['rec_id']])->find();
                    $return_num = M('return_goods')->where(['order_id'=>$v['order_id'],'status'=>['neq',3],'goods_id'=>$v['goods_id'],'spec_key'=>$v['spec_key']])->sum('goods_num');
                    if($v['goods_num'] > round($order_goods['goods_num'])-round($return_num)){
                        // if($v['goods_num'] > $order_goods['goods_num']-$return_num){
                        $return_arr = array('code' => 0, 'msg' => '添加失败,退货数超出订单数量', 'data' => []);
                        exit(json_encode($return_arr));
                    }
                    if($v['goods_num'] > $order_goods['goods_num']){
                        $v['goods_num'] = $order_goods['goods_num'];
                    }
                    if($v['goods_num'] > 0){
//                    $store = M('store')->where(['store_id'=>$v['store_id']])->find();
//                    if($store && $store['open_return'] == 0){
//                        $return_arr = array('code' => 0, 'msg' => '该店铺已经关闭售后', 'data' => []);
//                        exit(json_encode($return_arr));
//                    }
                        $order = M('order o')
                            ->field('o.*,u.fenbu_id as fenbu_id')
                            ->join('ty_users u on u.user_id = o.user_id','LEFT')
                            ->where(['o.order_id'=>$v['order_id']])
                            ->find();

                        $getorder = 0;
                        $a = M('return_goods')->add([
                            'order_sn'=>$order['order_sn'],
                            'return_order_sn'=>$order_sn,
                            'order_id'=>$v['order_id'],
                            'fenbu_id'=>$order['fenbu_id'],
                            'goods_id'=>$v['goods_id'],
                            'user_id'=>$order['user_id'],
                            'store_id'=>$v['store_id'],
                            'goods_num'=>$v['goods_num'],
                            'remark'=>$return_remark,
                            'addtime'=>time(),
                            'tuihuo_time'=>time(),
                            'member_goods_price'=>$v['member_goods_price'] - $v['yijia'],
                            'points'=>$v['points'],
                            'reason'=>'',
                            'spec_key'=>$v['spec_key'],
                            'yijia'=>$v['yijia'],
                            'driver_id'=>$order['driver_id'],
                            'getorder'=>$getorder,
                            'is_app'=>1,
                            'imgs'=>$imageUrl??''
                        ]);
                    }
//                    else{
//                        $return_arr = array('code' => 0, 'msg' => '请填下数量', 'data' => []);
//                        exit(json_encode($return_arr));
//                    }
                    //$tui_jifen+=($v['member_goods_price'] + $v['yijia'])*$v['goods_num'];

                }

                M()->commit();
                //开始退积分
                //accountLog($order['user_id'],0,-$tui_jifen,'订单 '.$order['order_sn'].' 退货扣的积分！',0,$order['order_id']);
                $return_arr = array('code' => 1, 'msg' => '操作成功', 'data' => $a);
                exit(json_encode($return_arr));
            }else{
                $return_arr = array('code' => 0, 'msg' => '添加失败,数据为空', 'data' => []);
                exit(json_encode($return_arr));
            }
        }catch (Exception $e){
            M()->rollback();
            Log::record($e->getMessage(),'ERR');
            $return_arr = array('code' => 0, 'msg' => '添加失败', 'data' => []);
            exit(json_encode($return_arr));
        }

    }
        /**
    *获取是否存在账号
    */
    
    public function platform(){
        $mobile = I('mobile');
         if(empty($mobile)){
            $return_arr = array('code' => 0, 'msg' => '获取失败', 'data' => []);
            exit(json_encode($return_arr));
        }
        //检测是否存在这个账号，先检测users表，在检测是否为商家
        $userInfo = M('users')->where(['mobile'=>$mobile])->find();
        $data = [];
        if(!empty($userInfo)){
            $data = $userInfo;
            $data['status'] = 2;
             //在检测是否为商家
            $store = M('store s')
            ->field('s.store_id,s.store_name,r.seller_name')
            ->join('ty_seller r on r.store_id = s.store_id','left')
            ->where(['s.user_id'=>$userInfo['user_id']])
            ->find();
          
            if(!empty($store)){
                $data['status'] = 1;
                $data['store_name'] = $store['store_name'];
                $data['seller_name'] = $store['seller_name'];
            }
        }
        if(!empty($data)){
            $return_arr = array('code' => 1, 'msg' => '获取成功', 'data' => $data);
            exit(json_encode($return_arr));
        }else{
            $return_arr = array('code' => 0, 'msg' => '获取失败', 'data' => []);
            exit(json_encode($return_arr));
        }
        
    }
    
         /*
	 *异常订单
	 */
    public function unusual(){
        
        $condition = array();
        $myw=' ';
        $page = I('page',1);
        $limit = I('limit',20);
        if($page == 1){
            $page = 0;
        }else{
            $page = $page-1;
        }
        $showPage = $page*$limit;
       
        I('kehu') ? $condition['c.company'] = array('like','%'.trim(I('kehu')).'%') : false;
        // I('shanghu') ? $condition['d.store_name'] = array('like','%'.trim(I('shanghu')).'%') : false;
        $condition['a.store_id'] = STORE_ID;
        $myw = ' and d.store_id='.STORE_ID;
        I('order_sn') ? $condition['order_sn'] =  array('like','%'.trim(I('order_sn')).'%') : false;
//        I('shipping_status') != '' ? $condition['shipping_status'] = I('shipping_status') : false;

//        $condition['a.order_status'] = 1;//判断要列出的订单状态
        $condition['_string'] = '( a.jian_count > 0 and a.ruku_count != a.jian_count and a.ruku_count > 0) or (a.pda_qdzt = 1)';

        if(I('biaoshi_xian')){
            $condition['c.biaoshi_xian'] = I('biaoshi_xian');
            $myw.=' and c.biaoshi_xian="'.I('biaoshi_xian').'"';
        }


        if(I('tag')){
            if(I('tag') == 1){
                $condition['a.tag_price'] = ['eq',0];
                $myw.=" AND a.tag_price = 0 ";
            }else{
                $condition['a.tag_price'] = ['neq',0];
                $myw.=" AND a.tag_price <> 0 ";
            }
        }


        $timegap = I('timegap');
    
        if($timegap){
            $gap = explode(' ~ ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $lastweek = date('Y-m-d',strtotime("-15 day"));//30天前-1 month
            $begin = I('begin',$lastweek);
            $end =  I('end',date('Y-m-d'));
        }

        if($begin && $end){
            $condition['a.add_time'] = array('between',array(strtotime($begin),strtotime($end)));
            $myw.=' and a.add_time > '.strtotime($begin).' and  a.add_time < '.strtotime($end) ;
        }

       
        //获取订单列表
        $orderList = M('order a')
            ->field('a.order_id,a.user_id,c.nickname,c.company,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian')
            ->join('ty_users c on a.user_id=c.user_id','LEFT')
            ->join('ty_store d on a.store_id=d.store_id','LEFT')
            ->where($condition)
            ->limit($showPage,$limit)
            ->order('a.order_id desc')
            ->group('a.user_id')->select(); //过滤获取主订单

  
        foreach($orderList as $key=>$v) { //整理子单
            $order_list = M('order a')
                ->field('a.order_id,a.pda_qdzt,a.order_status,a.jian_count,a.ruku_count as ruku_count,a.total_amount,a.order_sn,a.store_id,a.jian_count,a.order_amount,a.pda_qdzt,a.tag_price,c.nickname,c.company,d.store_name,CONCAT(c.biaoshi_xian,if(c.fast_flag="1","快","")) as biaoshi_xian,a.ruku_count,a.chuku_count,a.is_checkout,a.admin_note,a.ruku_last_time')
                ->join('ty_users c on a.user_id=c.user_id', 'LEFT')
                ->join('ty_store d on a.store_id=d.store_id', 'LEFT')
                ->where('a.user_id=' . $v['user_id'] . ' and  a.jian_count > 0 and a.ruku_count != a.jian_count and a.ruku_count>0'. $myw)
                ->group('a.order_id')
//                 ->group('b.order_id')
                ->order('a.order_id desc')
                ->select(); //过滤获取主订单

            $xiaoji = 0;
            foreach ($order_list as $keys => $values) { //整理子单
                $rukunum = $values['ruku_count'];
                $chukunum = $values['chuku_count'];
                $order_list[$keys]['ruku'] = $rukunum;
                $order_list[$keys]['chuku'] = $chukunum;
                $order_list[$keys]['pda_online'] = $values['pda_online']!=0 ?$values['pda_online'] : $values['order_amount'];
                
                $order_jian = M('order_jian')->where(['order_id'=>$values['order_id'],'status_r'=>0])->select();
                $order_jian_msg = '';
                foreach ($order_jian as $k=>$val){
                    $order_jian_msg .= $val['ruku_num'].',';
                }
                $order_jian_msg .= '还没验收';
                $order_list[$keys]['order_jian_msg'] = $order_jian_msg;
//                 $pda_online +=$order_list[$keys]['pda_online'];
//                 $pda_offline += $values['pda_offline'];
                $xiaoji += sanwei($values['order_amount']);
                $zongji+=$values['order_amount']+$values['yijia_heji'];
            }
            $orderList[$key]["xiaoji"] = $xiaoji;
            $orderList[$key]["order_list"] = $order_list;
        }
        
        $json = [];
        $json['code'] = 1;
        $json['msg'] = '获取成功';
        $json['data'] = ['page'=>I('page'),'limit'=>$limit,'data'=>$orderList];
        $this->ajaxReturn($json);
   
    }
    
    
            /**
     * 商家作废订单
     * */
     public function cancelOrder(){
        $orderLogic = new OrderLogic();
         $order_id = I('order_id');
         $orderLogic->orderProcessHandle($order_id,'invalid',STORE_ID);
         $json = [];
        $json['code'] = 1;
        $json['msg'] = '操作成功';
        $json['data'] = [];
        $this->ajaxReturn($json);
     }
     
     public function ajaxReturn($data){
         exit(json_encode($data));
     }
}